Qt学习笔记-使用shape() 使得碰撞更加精确
生活随笔
收集整理的這篇文章主要介紹了
Qt学习笔记-使用shape() 使得碰撞更加精确
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
官方解析如下:
這英語就我就不翻譯了,就他說的,很好理解,
我就直接來個例子好了。
運行截圖如下:
代碼如下:
myitem.h
#ifndef MYITEM_H #define MYITEM_H#include <QGraphicsItem>class MyItem:public QGraphicsItem { public:MyItem();QRectF boundingRect()const;void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);void setColor(const QColor &color);QPainterPath shape()const;void setMyFlag(bool flag);bool getMyFlag();void changeMyFlag();protected:void mousePressEvent(QGraphicsSceneMouseEvent *event);void keyPressEvent(QKeyEvent *event);private:QColor m_color;bool m_flag; };#endif // MYITEM_Hmyitem.cpp
#include "myitem.h" #include <QPainter> #include <QCursor> #include <QKeyEvent> #include <QGraphicsView> #include <QDebug> #include <QPainterPath>MyItem::MyItem() {m_color=Qt::black;setFlag(QGraphicsItem::ItemIsFocusable);setFlag(QGraphicsItem::ItemIsMovable); }QRectF MyItem::boundingRect()const{qreal penWidth=1;return QRectF(0-penWidth/2,0-penWidth/2,100+penWidth,100+penWidth); }void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){Q_UNUSED(option)Q_UNUSED(widget)painter->setBrush(m_color);painter->drawEllipse(0,0,100,100); }void MyItem::setColor(const QColor &color){m_color=color; }QPainterPath MyItem::shape() const {QPainterPath path;path.addEllipse(boundingRect());return path; }void MyItem::setMyFlag(bool flag){m_flag=flag; }bool MyItem::getMyFlag() {return m_flag; }void MyItem::changeMyFlag(){m_flag=!m_flag; }void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *event){Q_UNUSED(event)setFocus();setCursor(Qt::ClosedHandCursor); }void MyItem::keyPressEvent(QKeyEvent *event){if(event->key()==Qt::Key_Down){moveBy(0,10);}else if(event->key()==Qt::Key_Up){moveBy(0,-10);}else if(event->key()==Qt::Key_Left){moveBy(-10,0);}else{moveBy(10,0);}QList<QGraphicsItem*>list=collidingItems();if(!list.isEmpty()){if(((MyItem*)(list.at(0)))->getMyFlag()==true){((MyItem*)(list.at(0)))->setColor(Qt::blue);((MyItem*)(list.at(0)))->changeMyFlag();((MyItem*)(list.at(0)))->update();}else{((MyItem*)(list.at(0)))->setColor(Qt::red);((MyItem*)(list.at(0)))->changeMyFlag();((MyItem*)(list.at(0)))->update();}} }main.cpp
#include <QApplication> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QGraphicsView> #include "myitem.h"int main(int argc, char *argv[]) {QApplication a(argc, argv);QGraphicsScene scene;MyItem *item=new MyItem;MyItem *item2=new MyItem;scene.addItem(item);scene.addItem(item2);item->setPos(100,100);item2->setPos(300,300);item->setColor(Qt::red);item2->setColor(Qt::blue);scene.setSceneRect(0,0,700,500);QGraphicsView view(&scene);view.resize(700,500);view.show();view.centerOn(item);return a.exec(); }總結
以上是生活随笔為你收集整理的Qt学习笔记-使用shape() 使得碰撞更加精确的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux工作笔记-使用SCP文件协议(
- 下一篇: Qt工作笔记-第三种方法在QGraphi