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

自定义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();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值