自定义QGraphicsItem
1 #include <QtWidgets> 2 //自定义item需要重写的两个函数boudingRect()和paint() 3 class CheckBoxItem : public QGraphicsObject 4 { 5 Q_OBJECT 6 public: 7 CheckBoxItem(int w, int h, const QString &text, const QString &checkedIcon, const QString &emptyIcon, QGraphicsObject *parent = 0); 8 QRectF boundingRect()const override; //用来设置该item的大小 必须 9 void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;//用来绘制该item的东西 必须 10 bool isChecked(); 11 void setChecked(bool checked); 12 signals: 13 void stateChanged(bool checked); 14 protected: 15 void keyPressEvent(QKeyEvent * event) override; 16 void mousePressEvent(QGraphicsSceneMouseEvent *event) override; 17 void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; 18 private: 19 QString m_text; 20 int m_width; 21 int m_height; 22 bool m_checked; 23 QPixmap m_checkedIcon; 24 QPixmap m_emptyIcon; 25 bool m_leftButtonDown; 26 }; 27 28 CheckBoxItem::CheckBoxItem(int w, int h, const QString &text, const QString &checkedIcon, const QString &emptyIcon, QGraphicsObject *parent) : 29 m_width(w), 30 m_height(h), 31 m_text(text), 32 m_checkedIcon(checkedIcon), 33 m_emptyIcon(emptyIcon), 34 QGraphicsObject(parent), m_leftButtonDown(false) 35 { 36 setFlag(QGraphicsItem::ItemIsFocusable, true); //用来设置这个item可以获取焦点 37 } 38 QRectF CheckBoxItem::boundingRect() const 39 { 40 return QRectF(0,0, m_width, m_height); 41 } 42 //调用这里面的painter画家进行绘制图形 43 void CheckBoxItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) 44 { 45 Q_UNUSED(option) 46 Q_UNUSED(widget)//这个宏是用来把不用到的参数注掉的功能 47 int x = 2; 48 int y = (m_height - m_checkedIcon.height()) / 2; 49 painter->drawPixmap(x, y, m_checked ? m_checkedIcon : m_emptyIcon); 50 if(!m_text.isEmpty()) 51 { 52 x = x + m_checkedIcon.width() + 4; 53 QRect rc(x, 0, m_width - x - 2, m_height); 54 painter->drawText(rc, Qt::AlignVCenter | Qt::AlignLeft, m_text); 55 } 56 } 57 void CheckBoxItem::keyPressEvent(QKeyEvent *event) 58 { 59 if(event->key() == Qt::Key_Space) 60 { 61 event->accept(); 62 m_checked = !m_checked; 63 update(); 64 } 65 } 66 void CheckBoxItem::mousePressEvent(QGraphicsSceneMouseEvent *event) 67 { 68 if(event->button() == Qt::LeftButton) 69 { 70 m_leftButtonDown = true; 71 event->accept(); 72 } 73 } 74 void CheckBoxItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) 75 { 76 if(event->button() == Qt::LeftButton) 77 { 78 m_leftButtonDown = false; 79 m_checked = !m_checked; 80 event->accept(); 81 update(); 82 emit stateChanged(m_checked); 83 } 84 }