我尝试通过moveBy()移动QGraphicsItem“box”。如果我将keyPressEvent放在item类中 - 它可以工作,但如果我将此函数放在mainwindow类中并尝试通过指针调用moveBy()函数 - 它不起作用。我做错了什么?
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;
}
}
答案 0 :(得分:0)
您确定当您按下按键时,您的程序甚至会转到MainWindow::keyPressEvent(QKeyEvent *event)
吗?尝试在qDebug() << "mouse key press in mainwindow";
方法中调试或添加类似MainWindow::keyPressEvent(QKeyEvent *event)
的smth。
您的小部件需要抓取鼠标事件来处理此事件。我很确定它不会gr mouse老鼠。还需要关注另一个词。