Solved Why do I not get any MouseEvents in a QGraphicsItem derived class?
-
Hi! The following works with Qt 5.9. It prints "Item" if you click on a custom item, and it prints "Nothing" if you click on empty space in the custom view.
myview.h
#ifndef MYVIEW_H #define MYVIEW_H #include <QGraphicsView> class MyView : public QGraphicsView { public: MyView(QWidget *parent = Q_NULLPTR); protected: virtual void mousePressEvent(QMouseEvent *event) override; }; #endif // MYVIEW_H
myview.cpp
#include "myview.h" #include <QMouseEvent> #include <QGraphicsItem> #include <QDebug> MyView::MyView(QWidget *parent) : QGraphicsView(parent) { } void MyView::mousePressEvent(QMouseEvent *event) { if (!itemAt(event->pos())) { qDebug("Nothing"); } QGraphicsView::mousePressEvent(event); }
myitem.h
#ifndef MYITEM_H #define MYITEM_H #include <QGraphicsItem> class MyItem : public QGraphicsItem { public: MyItem(QGraphicsItem *parent = Q_NULLPTR); virtual QRectF boundingRect() const override; virtual void paint(QPainter *painter, QStyleOptionGraphicsItem const *, QWidget *) override; protected: virtual void mousePressEvent(QGraphicsSceneMouseEvent *) override; }; #endif // MYITEM_H
myitem.cpp
#include "myitem.h" #include <QPainter> #include <QDebug> MyItem::MyItem(QGraphicsItem *parent) : QGraphicsItem(parent) { } QRectF MyItem::boundingRect() const { auto const penWidth = 1.0; return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth); } void MyItem::paint(QPainter *painter, QStyleOptionGraphicsItem const *, QWidget *) { painter->setBrush(QBrush(QColor("orange"))); painter->setPen(QColor("lime")); painter->drawRect(-10, -10, 20, 20); } void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *) { qDebug() << "Item"; }
-
@Wieland
Ok, thank you!
I tried it in my project, it didn't work in version 5.8 so I downloaded 5.9.1 and now I'm unfortunately having problems with the Qt version. It says, this is Qt version 5.9.1 for Android (?) and it can't build and run my project. I downloaded and installed the normal version, not for Android... Phew I don't know, I will look and update when I have it (I hate it when I can't continue a project because of such unnessecary problems -.- ) -
I'm sorry to hear that :-/ But I'm sure it works with 5.8, too. I only mentioned 5.9 because I thought you might be using 4.7 or older.
-
This post is deleted! -
@Wieland
Ok, I reinstalled it and added the things I needed (I hope) and made a new project with your code (and some additional lines) and it worked. But my big project still does not work and so far, I cant find the mistake. However I tried to do the procedure nearly the same as in your example, it does not work yet -
This post is deleted! -
This post is deleted! -
This post is deleted! -
This post is deleted! -
The final answer for all these problems is there:
https://forum.qt.io/topic/82085/qgraphicsview-mousereleaseevent-ensures-that-i-can-t-select-qgraphicsitems-anymore/2