您的位置:首页 > 产品设计 > UI/UE

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

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

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

//paintlabel.h文件
#ifndef PAINTLABEL_H
#define PAINTLABEL_H
#include <QLabel>

class PaintLabel:public QLabel
{
Q_OBJECT
public:
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);


将其修改为载入一幅图片进行实验。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: