欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt图形视图框架(三) 自定义QGraphicsItem

程序员文章站 2024-03-26 09:57:59
...

自定义QGraphicsItem

目的:通过按空格或点击鼠标左键实现两张图片之间的切换
头文件:
#ifndef CHECKBOX_H
#define CHECKBOX_H

#include <QtWidgets>

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 <QDebug>

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 <QtWidgets>
#include <QApplication>
#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();
}