我在让QGraphicsView中的事件工作时遇到了问题。我对QGraphicsView进行了子类化,并尝试重载mousePressEvent和wheelEvent。但是mousePressEvent和wheelEvent都不会被调用。
这是我的代码(现在编辑了一些东西):
声明:
#include <QGraphicsView>
#include <QGraphicsScene>
class rasImg: public QGraphicsView
{
public:
rasImg(QString file);
~rasImg(void);
initialize();
QGraphicsView *view;
QGraphicsScene *scene;
private:
virtual void mousePressEvent (QGraphicsSceneMouseEvent *event);
virtual void wheelEvent ( QGraphicsSceneMouseEvent * event );
}定义:
#include "rasImg.h"
void rasImg::initialize()
{
view = new QGraphicsView();
scene = new QGraphicsScene(QRect(0, 0, MaxRow, MaxCol));
scene->addText("HELLO");
scene->setBackgroundBrush(QColor(100,100,100));
view->setDragMode(QGraphicsView::ScrollHandDrag);
view->setScene(scene);
}
void rasImg::mousePressEvent (QGraphicsSceneMouseEvent *event)
{
qDebug()<<"Mouse released";
scene->setBackgroundBrush(QColor(100,0,0));
}
void rasImg::wheelEvent ( QGraphicsSceneMouseEvent * event )
{
qDebug()<<"Mouse released";
scene->setBackgroundBrush(QColor(100,0,0));
}那么,我做错了什么呢?
当我单击视图或使用鼠标滚轮时,为什么看不到消息或背景颜色变化?
发布于 2011-05-07 21:19:07
您无法获得事件,因为它们是由您创建的scene对象处理的,而不是您的类。
从rasImg中删除QGraphicsScene *scene;,并对构造函数尝试如下所示:
rasImg::rasImg(QString file)
: QGraphicsScene(QRect(0, 0, MaxRow, MaxCol))
{
addText("HELLO");
setBackgroundBrush(QColor(100,100,100));
setDragMode(QGraphicsView::ScrollHandDrag);
view = new QGraphicsView();
view->setScene(this);
}如果你想在两个步骤中做到这一点,你可以做:
rasImg::rasImg(QString file)
: QGraphicsScene()
{
// any constructor work you need to do
}
rasImg::initialize()
{
addText("HELLO");
setSceneRect(QRect(0, 0, MaxRow, MaxCol));
setBackgroundBrush(QColor(100,100,100));
setDragMode(QGraphicsView::ScrollHandDrag);
view = new QGraphicsView();
view->setScene(this);
}关键是显示的场景必须是rasImg的实际实例,而不是QGraphicsScene的实例。
如果这是你的子类化的视图,做同样的事情。显示的视图必须是类的实例,而不是普通的QGraphicsView。
rasImg::rasImg(QString file)
: QGraphicsView()
{
// constructor work
}
void rasImg::initialize()
{
scene = new QGraphicsScene(QRect(0, 0, MaxRow, MaxCol));
scene->addText("HELLO");
scene->setBackgroundBrush(QColor(100,100,100));
setDragMode(QGraphicsView::ScrollHandDrag);
setScene(scene);
}发布于 2011-05-07 21:52:22
QGraphicsView由QWidget派生而来。因此,它会像接收常规窗口小部件一样接收鼠标事件。如果你的代码确实是
void rasImg::mousePressEvent (QGraphicsSceneMouseEvent *event)它不能接收事件,因为它应该是
void rasImg::mousePressEvent ( QMouseEvent *event )QGraphicsSceneMouseEvent用于QGraphicsScene中接收鼠标输入的项。
发布于 2012-07-25 20:37:47
如果你想处理特定图形用户界面元素上的点击,而不是整个场景上的点击,你应该从QGraphicsItem (参见SimpleClass here示例)或从现有元素之一(例如QGraphicsPixmapItem )派生自己的类。
在这两种情况下,您都可以在派生类中重写void mousePressEvent(QGraphicsSceneMouseEvent *event);
https://stackoverflow.com/questions/5921289
复制相似问题