QGraphicsPixmapItem not selectable

2019-07-16 16:17发布

问题:

I want my QGraphicsPixmapItem become selectable (i.e. clickable in more general way) on QGraphicScene but it doesn't. I'm actually modifying Qt's Diagram Scene sample, where QGraphicsItem's subclass is used and is selectable. I appreciate your help.

cpp code (partial):

#include <iostream>
#include <QtGui>    
#include "overlayPixmapItem.h"

OverlayPixmapItem::OverlayPixmapItem(DiagramType diagramType, QMenu *contextMenu,
                                                   QPixmap img, QGraphicsItem *parent,
                                                   QGraphicsScene *scene)
    : QGraphicsPixmapItem(img, parent), QObject()
{
    myDiagramType = diagramType;
    myContextMenu = contextMenu;

    this->setAcceptsHoverEvents(true);
    this->setAcceptHoverEvents(true); //
    this->setAcceptedMouseButtons(Qt::LeftButton);
    this->setAcceptedMouseButtons(Qt::RightButton);
    this->acceptDrops();

    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    this->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
}
:

header (partial):

#ifndef OVERLAYPIXMAPITEM_H
#define OVERLAYPIXMAPITEM_H

#include <QGraphicsPixmapItem>
#include <QList>
#include <QObject>

class QPixmap;
class QGraphicsItem;
class QGraphicsScene;
class QTextEdit;
class QGraphicsSceneMouseEvent;
class QMenu;
class QGraphicsSceneContextMenuEvent;
class QPainter;
class QStyleOptionGraphicsItem;
class QWidget;
class QPolygonF;

class OverlayPixmapItem : public QObject, public QGraphicsPixmapItem
{
        Q_OBJECT

    public:
        enum { Type = UserType + 15 };
        enum DiagramType { Crosshair };

        OverlayPixmapItem(DiagramType diagramType, QMenu *contextMenu,
                                 QPixmap img, QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);

        DiagramType diagramType() const { return myDiagramType; }
        QPolygonF polygon() const { return myPolygon; }
        int type() const { return Type;}

    protected:
        void contextMenuEvent(QGraphicsSceneContextMenuEvent *event);
        QVariant itemChange(GraphicsItemChange change, const QVariant &value);
        void hoverEnterEvent ( QGraphicsSceneHoverEvent * event );
        void hoverLeaveEvent ( QGraphicsSceneHoverEvent * event );

    public: signals:
        void mouseHoveredOnElem(OverlayPixmapItem *i);
        void mouseHoveredOutOfElem(OverlayPixmapItem *i);

    private:
        DiagramType myDiagramType;
        QPolygonF myPolygon;
        QMenu *myContextMenu;
};
#endif // OVERLAYPIXMAPITEM_H

回答1:

As pointed out in my first comment, you call setAcceptedMouseButtons() method twice. While the first call actually set the correct button to be accepted, the second call make this setting lost.

To accept both buttons on this item, you have to combine Qt MouseButtons flags, this way :

item->setAcceptedMouseButtons(Qt::LeftButton|Qt::RightButton) ;