使用moveBy移动QGraphicsItem
问题描述:
我尝试通过moveBy()移动QGraphicsItem“box”。如果我将keyPressEvent放在item类中 - 这是可行的,但是如果我将此函数放在mainwindow类中并尝试通过指针调用moveBy()函数 - 它不起作用。我究竟做错了什么?使用moveBy移动QGraphicsItem
item.h:
#ifndef ITEM_H
#define ITEM_H
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QKeyEvent>
class item: public QGraphicsItem
{
public:
//virtual void keyPressEvent(QKeyEvent *event);
item(QGraphicsItem *parent =NULL);
QRectF boundingRect() const;
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget);
};
#endif // ITEM_H
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "item.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
item *box;
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
virtual void keyPressEvent(QKeyEvent *event);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
item.cpp:
#include "item.h"
item::item(QGraphicsItem *parent): QGraphicsItem(parent)
{
setFlag(QGraphicsItem::ItemIsFocusable);
}
QRectF item::boundingRect() const
{
return QRectF(0,0,200,200);
}
void item::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->drawPixmap(1,1, QPixmap(":/Graphics/Untitled.png"));
}
/*
void item::keyPressEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Right:
moveBy(3,0);
break;
case Qt::Key_Left:
moveBy(-3,0);
break;
case Qt::Key_Up:
moveBy(0,-3);
break;
case Qt::Key_Down:
moveBy(0,3);
break;
}
}
*/
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QGraphicsScene"
#include "QGraphicsView"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QGraphicsScene *scene = new QGraphicsScene;
box = new item;
scene->addItem(box);
QGraphicsView *view = new QGraphicsView;
view->setScene(scene);
view->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
switch(event->key())
{
case Qt::Key_Right:
box->moveBy(3,3);
break;
case Qt::Key_Left:
break;
case Qt::Key_Up:
break;
case Qt::Key_Down:
break;
}
}
答
当你按下键时,你确定你的程序甚至达到了MainWindow::keyPressEvent(QKeyEvent *event)
?尝试调试或在您的MainWindow::keyPressEvent(QKeyEvent *event)
方法中将这样的qDebug() << "mouse key press in mainwindow";
放在这样的位置。
您的小部件需要抓取鼠标事件来处理此事件。我很确定这不是啃老鼠。还有一句话需要关注。