项目中遇到的问题。
#include <QApplication>
#include <QPushButton>
const QPixmap pixmap(":/image/car.png");
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QPushButton button;
button.setIcon(QIcon(pixmap));
button.show();
return a.exec();
}
运行该段程序后出现了错误提示就异常退出了。
QPixmap: Must construct a QGuiApplication before a QPixmap.
QPixmap:必须在QPixmap之前构造一个QGuiApplication。
既然报关于QPixmap的错误提示,我们先找找QPixmap的官方文档吧。找了一遍,找到了一个有点关系的注意事项:
Note: When using the native X11 graphics system, the pixmap becomes invalid when the QApplication instance is destroyed.
注意:使用本机X11图形系统时,销毁QApplication实例后,像素图将会无效。
并不能解释上面的运行时错误的原因。既然QPixmap没什么发现,那么就找找它的继承父类(QPaintDevice)吧。
在QPaintDevice帮助文档中找到了下面解释:
Warning: Qt requires that a QGuiApplication object exists before any paint devices can be created. Paint devices access window system resources, and these resources are not initialized before an application object is created.
警告:在创建任何绘画设备之前,Qt要求先存在QGuiApplication对象。
绘图设备访问窗口系统资源,并且在创建应用程序对象之前是不会初始化这些资源。
顺便也找下Qt源码的错误出处:
QPixmap::QPixmap(const QString& fileName,...)
: QPaintDevice()
{
...
if (!qt_pixmap_thread_test())
return;
...
}
static bool qt_pixmap_thread_test()
{
if (Q_UNLIKELY(!QCoreApplication::instance())) {
qFatal("QPixmap: Must construct a QGuiApplication before a QPixmap");
return false;
}
...
return true;
}
哦,原来是这样。要创建QGuiApplication/QApplication之后才能去实例化QPaintDevice(QPixmap)。
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
const QPixmap pixmap(":/Image/backspace.png");
QPushButton button;
button.setIcon(QIcon(pixmap));
button.show();
return a.exec();
}
另外QPaintDevice的派生类都需要遵循,如:
QImage
QOpenGLPaintDevice
QPagedPaintDevice
QPaintDeviceWindow
QPicture
QPixmap
君君在实际使用中Qt的某些类内用到QPaintDevice或其派生类也需要遵循,如:
QIcon