在 Qt 中,显示图片通常使用 QLabel 和 QPixmap 进行图像的加载和显示。QPixmap 是专门用于显示图像的类,而 QLabel 则是一个可以容纳图片的小部件。
1、使用 QLabel 和 QPixmap 来显示图片:
1、加载图片
QPixmap pixmap(":/images/sample.png"); // 图片路径,可以是绝对路径或资源文件路径
2、设置 QLabel 的内容为 QPixmap
imageLabel->setPixmap(pixmap);
3、自动适应 QLabel 的大小
imageLabel->setScaledContents(true);
4、设置窗口布局
QVBoxLayout *layout = new QVBoxLayout(this);
5、代码展示
#include <QApplication>
#include <QLabel>
#include <QPixmap>
#include <QVBoxLayout>
#include <QWidget>
class ImageWindow : public QWidget {
public:
ImageWindow() {
QLabel *imageLabel = new QLabel(this); // 创建 QLabel 用于显示图片
// 加载图片
QPixmap pixmap(":/images/sample.png"); // 图片路径,可以是绝对路径或资源文件路径
// 设置 QLabel 的内容为 QPixmap
imageLabel->setPixmap(pixmap);
// 自动适应 QLabel 的大小
imageLabel-