qt中在QLabel上显示图像并画矩形框。

最主要的是重写paintEvent()函数,下面直接看代码

mylabel.h

# pragma execution_character_set("utf-8")

#ifndef MYLABEL_H
#define MYLABEL_H
#include 
#include 
#include
#include
#include
#include
#include
#include
#include
#include
#include


using namespace std;
#define WIDTH  640
#define HEIGHT  360


class MyLabel : public QLabel
{
     Q_OBJECT
public:

    MyLabel(QWidget *parent = 0);


protected:
	void  paintEvent(QPaintEvent *event);

private slots :
	void  slotGetOneFrame(QImage img);

private:
	QImage wb_Image;
};

#endif // MYLABEL_H

mylabel.cpp

#include "mylabel.h"


MyLabel::MyLabel(QWidget *parent):QLabel(parent)
{
}

//接收sig_GetOneFrame信号,调用update在界面中显示图像
void MyLabel::slotGetOneFrame(QImage img)
{
	wb_Image = img;
	update(); //调用update将执行 paintEvent函数
}

void MyLabel::paintEvent(QPaintEvent *event)
{
	QLabel::paintEvent(event);

	//画出图像
	QPainter painter(this);

	if (wb_Image.size().width() <= 0) return;
	///将图像按比例缩放成和窗口一样大小
	QImage img = wb_Image.scaled(QSize(WIDTH, HEIGHT), Qt::IgnoreAspectRatio);
	int x = this->width() - img.width();
	int y = this->height() - img.height();
	painter.drawImage(QPoint(x, y), img); 

	// 画矩形框
	QPainter paint;
	paint.begin(this);

	paint.setPen(QPen(Qt::red, 1, Qt::SolidLine, Qt::RoundCap));
	paint.drawRect(QRect(50, 50, 200, 200));

	QString strText = QString::fromLocal8Bit("用双手成就你的梦想");;
	paint.drawText(250, 50, strText);

	paint.end();
}

其中用到了信号槽,大家注意到头文件中

private slots :
	void  slotGetOneFrame(QImage img);

这是槽函数,还需要一个信号函数,需要在解码类中声明,此函数不需要实现。

signals:
	void sig_GetOneFrame(QImage img);

然后初始化时连接信号槽即可:

	m_VideoDecode = new CDemuxingDecoding;
	connect(m_VideoDecode, SIGNAL(sig_GetOneFrame(QImage)), ui.showCurrentPicLabel, SLOT(slotGetOneFrame(QImage)));


你可能感兴趣的:(QT,c/c++)