• 5251阅读
  • 5回复

QGraphicsItem QGraphicsScene  QGraphicsView 的使用还真不会(自绘图响应键盘移动),很难弄哦! [复制链接]

上一主题 下一主题
离线vbroot
 

只看楼主 倒序阅读 楼主  发表于: 2012-12-26

想实现一自绘方块的移动,但是就不会搞。请各位高手指点一二。

1、自定义 QGraphicsItem 子类 MyGrItem代码如下:

    mygritem.h
  1. #ifndef MYGRITEM_H
  2. #define MYGRITEM_H
  3. #include <QGraphicsItem>
  4. #include <QPainter>
  5. #include <QKeyEvent>
  6. class MyGrItem : public QGraphicsItem
  7. {
  8. public:
  9.     MyGrItem();
  10.     QRectF boundingRect() const;   //新增加3成员函数
  11.     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
  12.     void keyPressEvent(QKeyEvent *event);
  13. };
  14. #endif // MYGRITEM_H
   mygritem.cpp
  1. #include "mygritem.h"
  2. MyGrItem::MyGrItem()
  3. {
  4. }
  5. QRectF MyGrItem::boundingRect() const
  6. {
  7.     qreal penWith=1;
  8.     return QRectF(-10-penWith/2,-10-penWith/2,20+penWith,20+penWith);
  9. }
  10. void MyGrItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
  11. {
  12.     painter->setBrush(Qt::red);
  13.     painter->drawRect(0,0,20,20);
  14. }
  15. void MyGrItem::keyPressEvent(QKeyEvent *event)
  16. {
  17.     switch (event->key()) {
  18.     case Qt::Key_Left:
  19.         moveBy(-20,0);
  20.         break;
  21.     case Qt::Key_Right:
  22.         moveBy(20,0);
  23.         break;
  24.     default:
  25.         break;
  26.     }
  27. }
2、在UI窗体中增加一个控件Graphics View

3、在Widget类中增加
protected:    QGraphicsScene scene;    MyGrItem *myitem;然后初始化
  1. Widget::Widget(QWidget *parent) :
  2.     QWidget(parent),
  3.     ui(new Ui::Widget)
  4. {
  5.     ui->setupUi(this);
  6.     myitem=new MyGrItem;
  7.     scene.addItem(myitem);
  8.     ui->graphicsView->setScene(&scene);
  9. }






离线chen12nan

只看该作者 1楼 发表于: 2012-12-26
先设置item的flags;
setFlags(ItemIsMovable | ItemIsSelectable);设置你画的方块的属性。这样就可以选中它了。
至于键盘移动效果可以设置再加上这个属性ItemIsFocusable;然后再实现keypresssEvent事件试试。
学习QT...痛苦并快乐着的.keep moving。
离线vbroot

只看该作者 2楼 发表于: 2012-12-27
多谢楼上指导!问题已解决。

在 MyGrItem 类的构造函数增加
setFlags(ItemIsMovable | ItemIsSelectable|ItemIsFocusable);

再在场景对象中设置焦点
scene.setFocusItem(myitem);

哈哈,方向键就能自由控件自绘的正方形了。那个妙啊!!!

真心感谢!!!
离线chen12nan

只看该作者 3楼 发表于: 2012-12-27
回 2楼(vbroot) 的帖子
你知道怎么把QMainWindow设置为透明吗?在linux系统下...
学习QT...痛苦并快乐着的.keep moving。
离线vbroot

只看该作者 4楼 发表于: 2012-12-28
  我的环境在 win7 下MINGW.
刚接触几天,还没有搞过透明的。
离线祥龙九霄

只看该作者 5楼 发表于: 2013-05-21
在构造函数中添加
setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
即可实现拖动功能。
快速回复
限100 字节
 
上一个 下一个