2

我希望我的QGraphicsPixmapItem成为可选择的(即以更一般的方式可点击),QGraphicScene但事实并非如此。我实际上正在修改Qt's Diagram Scene sample,其中QGraphicsItem使用了 's 子类并且是可选择的。我感谢您的帮助。

cpp代码(部分):

#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);
}
:

标题(部分):

#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
4

1 回答 1

2

正如我在第一条评论中指出的那样,您调用setAcceptedMouseButtons()了两次方法。虽然第一个呼叫实际上设置了正确的按钮以被接受,但第二个呼叫使此设置丢失。

要接受此项目上的两个按钮,您必须以这种方式组合 Qt MouseButtons 标志:

item->setAcceptedMouseButtons(Qt::LeftButton|Qt::RightButton) ;
于 2012-07-21T19:42:09.387 回答