Qt在IMX6ULL嵌入式系统中图片加载问题排查与解决(保姆级教学!)
在使用Qt开发IMX6ULL嵌入式系统的过程中,我遇到了图片加载的常见问题。本文将分享问题排查的详细过程和解决方案,希望能帮助遇到类似困难的开发者。
问题描述
开发过程中,发现Qt程序无法正常加载图片,常见的错误表现为:
QFile::exists()
返回false
- 图片无法显示
- 没有明确的错误提示
就是imx6ull开发板上没有任何图片,也没有保存信息。
我已经把图片放到对应的目录下了,就是没有显示。
原因分析:
排查步骤
1. 支持的图片格式检查
因为我一开始用的是jpg格式所以报错
使用 QImageReader::supportedImageFormats()
可以快速获取系统支持的图片格式:
这句代码很关键
qDebug() << "Supported image formats:" << QImageReader::supportedImageFormats();
输出结果:
输出结果显示支持的格式包括:
- bmp
位图文件,通常兼容性最好
- png
常用的无损压缩格式
- gif
支持动画的格式
- svg
矢量图形格式
- ico
图标文件
- pbm/pgm/ppm
便携式位图格式
- xbm/xpm
位图格式
2.文件路径验证
确保文件路径正确且具有访问权限:
图片移动进去必须是可写可读的
sudo chmod 777 6.bmp
qt代码部分
// 获取应用程序当前目录
QString currentPath = QCoreApplication::applicationDirPath();
QString imagePath = currentPath + "/6.bmp";
// 打印当前目录和完整路径
qDebug() << "Current directory:" << currentPath;
qDebug() << "Full image path:" << imagePath;
qDebug() << "File exists:" << QFile::exists(imagePath);
然后就解决问题了
完整步骤
创建工程
前缀为 /
我们构建工程一下发现就在我们的工程目录下了
其他代码不用改就改mainwindow.cpp代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDebug>
#include <QPixmap>
#include <QDir>
#include <QImageReader>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 获取应用程序当前目录
QString currentPath = QCoreApplication::applicationDirPath();
QString imagePath = currentPath + "/6.bmp";
// 打印当前目录和完整路径
qDebug() << "Current directory:" << currentPath;
qDebug() << "Full image path:" << imagePath;
qDebug() << "File exists:" << QFile::exists(imagePath);
// 检查支持的图像格式
qDebug() << "Supported image formats:" << QImageReader::supportedImageFormats();
QPixmap pixmap(imagePath);
if (pixmap.isNull()) {
qDebug() << "Failed to load image from:" << imagePath;
} else {
qDebug() << "Image loaded successfully from:" << imagePath;
qDebug() << "Image size:" << pixmap.width() << "x" << pixmap.height();
ui->label->setPixmap(pixmap);
ui->label->setScaledContents(true);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
编译运行就OK
PC端需要把图片放到/home/embedfire/qtdemo/build-PIC_test-Desktop_Qt_5_11_3_GCC_64bit-Release下
然后把图片和构建好的二进制文件移动到开发板的同一个目录下运行就没问题了
经验总结:
- 嵌入式系统图片加载需要特别注意文件路径和格式
- 优先使用 BMP 格式进行兼容性测试
- 使用 qDebug() 进行详细的日志记录
- 重新编译和部署程序后务必重新运行