QLabel使用setPixmap函数无法显示jpg图片的问题

  在Qt的QLabel控件中我们可以使用setPixmap函数显示图片。但很多时候我们会发现无法显示图片,导致该问题产生的原因有很多种,下面我们举出导致该现象产生的其中两种原因。

一、原因一:要被显示的图片路径含有中文,用户没有对中文进行转换

我们新建一个Qt工程,将下面的三个文件包含进来

main.cpp

#include "Label.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	Label w;
	w.show();
	return a.exec();
}

Label.h

#pragma once

#include <QLabel>
#include "ui_Label.h"

class Label : public QLabel
{
	Q_OBJECT

public:
	Label(QWidget *parent = Q_NULLPTR);
	~Label();

private:
	Ui::Label ui;
};

Label.cpp

#include "Label.h"

Label::Label(QWidget *parent)
	: QLabel(parent)
{
	ui.setupUi(this);
	this->setPixmap(QPixmap("Resources/小狗.jpg"));
}

Label::~Label()
{
}

工程的Resources目录下有图片“小狗.jpg”如下所示:

我们编译上述工程,运行。预期应该是可以显示“小狗.jpg”图片,但实际效果却如下所示:

导致上述问题产生的原因是:要被显示的图片路径(Resources/小狗.jpg)中含有中文。这个时候我们可以使用使用QString的fromLocal8Bit()函数,实现从本地字符集GBK到Unicode的转换。我们将Label.cpp的代码改成如下所示:

#include "Label.h"

Label::Label(QWidget *parent)
	: QLabel(parent)
{
	ui.setupUi(this);
	this->setPixmap(QPixmap(QString::fromLocal8Bit("Resources/小狗.jpg")));
}

Label::~Label()
{
}

重新编译,运行,效果如下:

可以看到,图片可以正常显示了。

二、原因二:使用了paintEvent函数

我们将上述Label.h改成

#pragma once

#include <QLabel>
#include "ui_Label.h"

class Label : public QLabel
{
	Q_OBJECT

public:
	Label(QWidget *parent = Q_NULLPTR);
	~Label();
	void paintEvent(QPaintEvent *);

private:
	Ui::Label ui;
};

将上述Label.cpp改成

#include "Label.h"
#include <QPainter>

Label::Label(QWidget *parent)
	: QLabel(parent)
{
	ui.setupUi(this);
	this->setPixmap(QPixmap(QString::fromLocal8Bit("Resources/小狗.jpg")));
}

Label::~Label()
{
}

void Label::paintEvent(QPaintEvent *)
{
	;
}

重新编译,运行,效果如下:

我们发现改动程序后,又无法显示图片了。导致该现象的原因是引入了paintEvent函数,引入该函数我们就没法再通过setPixmap函数显示图片了,我们只能通过QPainter显示图片了。

我们改动Label.h如下:

#pragma once

#include <QLabel>
#include "ui_Label.h"

class Label : public QLabel
{
	Q_OBJECT

public:
	Label(QWidget *parent = Q_NULLPTR);
	~Label();
	void paintEvent(QPaintEvent *);

private:
	Ui::Label ui;
	QPixmap m_image1;
};

改动Label.cpp如下:

#include "Label.h"
#include <QPainter>

Label::Label(QWidget *parent)
	: QLabel(parent)
{
	ui.setupUi(this);
	m_image1.load(QString::fromLocal8Bit("Resources/小狗.jpg"));
}

Label::~Label()
{
}

void Label::paintEvent(QPaintEvent *)
{
	QPainter painter(this);
	painter.drawPixmap(0, 0, this->width(), this->height(), m_image1);
}

重新编译,运行,我们发现又可以显示图片了,效果如下:

发布了54 篇原创文章 · 获赞 55 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/u014552102/article/details/89608279