QT中使用QPainter在ui子控件中绘图

来源:互联网 发布:ipad三维建模软件 编辑:程序博客网 时间:2024/05/18 17:40

在使用QT中的QPainter绘制图片时发现其只能够在当前类中执行绘制操作。本文介绍一下怎么实现在ui的子控件中用QPainter实现绘图。以QLabel为例:

1.在QT工程中新建一个类PaintLabel,继承自QLabel

//paintlabel.h文件
#ifndef PAINTLABEL_H#define PAINTLABEL_H#include <QLabel>class PaintLabel:public QLabel{    Q_OBJECTpublic:    explicit PaintLabel(QWidget *parent = 0);    void paintEvent(QPaintEvent *event);};#endif // PAINTLABEL_H
</pre><pre name="code" class="cpp">//paintlabel.c文件
<pre style="margin-top: 0px; margin-bottom: 0px;"><span style=" color:#000080;">#include</span><span style=" color:#c0c0c0;"> </span><span style=" color:#008000;">"paintlabel.h"</span>

#include <QPainter>
#include <QDebug>
#include <extern.h>
#include <QtWidgets/qframe.h>
#include <QWidget>
#include <sys/time.h>
PaintLabel::PaintLabel(QWidget *parent):QLabel(parent)
{
}
void PaintLabel::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    global_var::Cap_Image = global_var::Cap_Image.scaled(this->width(),this->height(),Qt::IgnoreAspectRatio);
    painter.drawImage(QPoint(0,0), global_var::Cap_Image);
    QLabel::paintEvent(event);

    //global_var::time_End = (double)clock();
    //qDebug()<<(global_var::time_End-global_var::time_Start)/1000;
    //global_var::time_Start = global_var::time_End;
}

2.在界面设计文件mainwindow.ui中拖入一个QLabel控件,右键->提升为->选择基类QLabel->名称为PaintLabel->输入h文件paintlabel.h->选中->提升。

3.原程序中的功能是载入QImage类型的global_var::CapImage图片。读者可以修改代码

painter.drawImage(QPoint(0,0), global_var::Cap_Image);

将其修改为载入一幅图片进行实验。


1 1