Qt 重写paintEvent事件画线

可以自定义一个类QtImageLabel继承于QLabel,重写paintEvent事件划线,写文字等。如果用 ui 设计,将 QLabel 控件提升为 QtImageLabel 类型即可。

QtImageLabel.h

protected:
    void paintEvent(QPaintEvent *) override;

QtImageLabel.cpp

#pragma execution_character_set("utf-8")

QtImageLabel::QtImageLabel(QWidget *parent)
    : QLabel(parent)
{
    setScaledContents(true);
    setAttribute(Qt::WA_QuitOnClose, false);
} 

void QtImageLabel::paintEvent(QPaintEvent *e)
{
    QLabel::paintEvent(e);
    QPainter painter(this);
    QRect rect = geometry();
    int c_x = rect.width() / 2;
    int c_y = rect.height() / 2;

    painter.setPen(QPen(Qt::red, 1));
    painter.drawLine(c_x, 0, c_x, c_y * 2);
    painter.drawLine(0, c_y, c_x * 2, c_y);
    painter.drawRect(c_x - 130, c_y - 100, 260, 200);
    painter.drawEllipse(c_x - 130, c_y - 100, 260, 200);

    painter.setPen(Qt::green);
    painter.drawRect(c_x - 200, c_y - 150, 400, 300);

    painter.setPen(Qt::red);
    painter.drawText(2*c_x - 50, 20, "字体显示");
}

主界面 QtImageShow.cpp

#include "QtImageShow.h"
#include "ui_QtImageShow.h"
#include "QPixmap"

#pragma execution_character_set("utf-8")


QtImageShow::QtImageShow(QWidget *parent)
    : QWidget(parent)
{
    ui = new Ui::QtImageShow();
    ui->setupUi(this);
    setWindowTitle("图像显式");
    setAttribute(Qt::WA_QuitOnClose, false);

#if 1
    // 跟随比例变化
    ui->label->setScaledContents(true);
    QPixmap pixmap("./01.png");
    //pixmap.load("./01.jpg");
    // 让图片大小适应控件大小, 如果不需要,可以直接显示原图
    QPixmap s_img = pixmap.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    //ui->label->setPixmap(s_img);
    ui->label->setPixmap(pixmap);
#endif
}

QtImageShow::~QtImageShow()
{
    delete ui;
}

void QtImageShow::paintEvent(QPaintEvent * e)
{
}

// 按钮,切换图片显示 01.png 02.png
void QtImageShow::on_pushButton_clicked()
{
    static int img_id{ 0 };
    img_id = img_id = std::abs(img_id - 1);
    QString path = QString("./0") + QString::number(img_id+1) + ".png";
    QPixmap pixmap(path);
    ui->label->setPixmap(pixmap);
}
posted @ 2024-11-20 10:03  double64  阅读(13)  评论(0编辑  收藏  举报