C++ 使用moveBy移动QGraphicsItem
我尝试通过moveBy移动QGraphicsItem框。若我将keyPressEvent放在item类中—它是工作的,但若我将此函数放在mainwindow类中并尝试通过指针调用moveBy函数—它不工作。我做错了什么 项目h:C++ 使用moveBy移动QGraphicsItem,c++,qt,C++,Qt,我尝试通过moveBy移动QGraphicsItem框。若我将keyPressEvent放在item类中—它是工作的,但若我将此函数放在mainwindow类中并尝试通过指针调用moveBy函数—它不工作。我做错了什么 项目h: #ifndef ITEM_H #define ITEM_H #include <QGraphicsItem> #include <QGraphicsView> #include <QKeyEvent> class item: pu
#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.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;
}
}
您确定您的程序在按键时会进入主窗口::keyPressEventQKeyEvent*事件吗?试着像qDebug一样调试或放置smth
#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;
}
}
*/
#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;
}
}