Qt图形视图框架(三) 自定义QGraphicsItem
自定义QGraphicsItem
头文件:
#ifndef CHECKBOX_H#define CHECKBOX_H#include class CheckBox : public QGraphicsItem {private: int w, h; QPixmap a, b; bool is_checked;public: CheckBox(int, int, const QString &, const QString &); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);protected: void mousePressEvent(QGraphicsSceneMouseEvent *); void mouseReleaseEvent(QGraphicsSceneMouseEvent *); void keyPressEvent(QKeyEvent *);};#endif // CHECKBOX_H
其源文件:
#include "checkbox.h"#include CheckBox::CheckBox(int w, int h, const QString &a, const QString &b) : w(w), h(h), a(a), b(b), is_checked(true) {}QRectF CheckBox::boundingRect() const { return QRectF(0, 0, 50, 50);}void CheckBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); QPixmap temp; if (is_checked) { qDebug() << "a"; temp = a.scaled(50, 50, Qt::KeepAspectRatioByExpanding); } else { qDebug() << "b"; temp = b.scaled(50, 50, Qt::KeepAspectRatioByExpanding); } painter->drawPixmap(0, 0, temp);}void CheckBox::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { event->accept(); }}void CheckBox::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { qDebug() << "mouse"; event->accept(); is_checked = !is_checked; update(); }}void CheckBox::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Space) { qDebug() << "key"; event->accept(); is_checked = !is_checked; update(); }}
main:
#include #include #include "checkbox.h"int main(int argc, char *argv[]){ QApplication app(argc, argv); QGraphicsScene *scene = new QGraphicsScene; QGraphicsView *view = new QGraphicsView; view->setScene(scene); CheckBox cb(50, 50, ":/image/a.jpg", ":/image/timg.jpg"); cb.setFlag(QGraphicsItem::ItemIsFocusable, true); cb.setFocus(); scene->addItem(&cb); view->show(); return app.exec();}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~