Search code examples
qttextwidgeticonsclickable

Displaying lot of pixmaps with a QLabel under them on a QGraphicsPixmap


I need a widget where i can place a variety of clickable icons and under those icons some text using QLabel.

This is an image: enter image description here

I know this will need some tweaking and sub-classing. What would be the best appropiate way to do this? I know that those clickable icons will be displayed on a QGraphicsView.


Solution

  • I suggest you use a QGraphicsView.

    Here is a sample for a clickable pixmap:

    ClickablePixmap::ClickablePixmap( QGraphicsItem* itemParent )
        : QObject(0)
        , QGraphicsPixmapItem(itemParent)
        , m_pressed(false)
    {
        setFlags(QGraphicsItem::ItemIsFocusable |
                 QGraphicsItem::ItemIsSelectable |
                 QGraphicsItem::ItemSendsGeometryChanges |
                 QGraphicsItem::ItemIgnoresParentOpacity
                 );
        setAcceptedMouseButtons(Qt::LeftButton);
        setCursor(Qt::ArrowCursor);
    }
    
    void ClickablePixmap::mouseReleaseEvent( QGraphicsSceneMouseEvent* event )
    {
        setCursor(Qt::ArrowCursor);
        m_pressed = false;
        update();
        if( boundingRect().contains(event->pos()) )
            emit clicked();
        event->accept();
    }
    
    void ClickablePixmap::mousePressEvent( QGraphicsSceneMouseEvent* event )
    {
        setCursor(Qt::ArrowCursor);
        m_pressed = true;
        update();
        QGraphicsPixmapItem::mousePressEvent(event);
    }
    
    void ClickablePixmap::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )
    {
        Q_UNUSED(option);
        Q_UNUSED(widget);
    
        QRect rect(0,0, boundingRect().width(), boundingRect().height());
    
        // Create the pushed effet
        if( m_pressed ) {
            rect.adjust(2,2,-2,-2);
        }
        painter->drawPixmap(rect, pixmap());
    }
    

    The next thing to do is to embed this widget into a container widget with a:

    QVBoxLayout
    

    Then you can add your QLabel underneath.