简体   繁体   中英

Which Qt class should I use to represent an image on a rectangle?

I have a self coded rectangle (not using QRect for educational purposes), which looks like so:

class Block {

private: // also has getters and setters for this stuff
    int m_x;
    int m_y;
    uint m_width;
    uint m_height;
    QColor m_color;

public:
    Block(int x = 0, int y = 0, uint w = 64, uint h = 64);
    Block(const QColor &color, int x = 0, int y = 0, uint w = 64, uint h = 64);

    void paint(QPainter &painter) const
    {
        painter.fillRect(m_x, m_y, m_width, m_height, m_color);
    }
};

Now I'd like to add a support for images, so the block can either have a color or an image (if both provided, image will be used). The problem is, there are too many classes to represent images ( QPixmap , QImage , QIcon ) and I have no idea which one should I use. What are the differences, which one is best suited for simply drawing a resource image into a rectangle?

If you want to display the image on screen, use QPixmap . If you want to modify image, load or save it to file, use QImage .

QIcon is based on QPixmap and provides ability to choose one of many pixmaps based on requested size and state. QIcon is probably not what you want.

From the documentation :

Qt provides four classes for handling image data: QImage, QPixmap, QBitmap and QPicture. QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. QBitmap is only a convenience class that inherits QPixmap, ensuring a depth of 1. Finally, the QPicture class is a paint device that records and replays QPainter commands.

The QIcon class provides scalable icons in different modes and states. A QIcon can generate smaller, larger, active, and disabled pixmaps from the set of pixmaps it is given. Such pixmaps are used by Qt widgets to show an icon representing a particular action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM