前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Qt使用QPixmap小坑

Qt使用QPixmap小坑

作者头像
Qt君
发布2023-03-17 14:31:09
1.6K0
发布2023-03-17 14:31:09
举报
文章被收录于专栏:跟Qt君学编程

项目中遇到的问题。

1. 下面的代码会有什么问题呢?

代码语言:javascript
复制
#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();
}

  运行该段程序后出现了错误提示就异常退出了。

代码语言:javascript
复制
QPixmap: Must construct a QGuiApplication before a QPixmap.
QPixmap:必须在QPixmap之前构造一个QGuiApplication。

2. 为什么会这样呢?

  既然报关于QPixmap的错误提示,我们先找找QPixmap的官方文档吧。找了一遍,找到了一个有点关系的注意事项:

代码语言:javascript
复制
Note: When using the native X11 graphics system, the pixmap becomes invalid when the QApplication instance is destroyed.
注意:使用本机X11图形系统时,销毁QApplication实例后,像素图将会无效。

  并不能解释上面的运行时错误的原因。既然QPixmap没什么发现,那么就找找它的继承父类(QPaintDevice)吧。

  在QPaintDevice帮助文档中找到了下面解释:

代码语言:javascript
复制
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源码的错误出处:

代码语言:javascript
复制
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)。

3. 修正后的代码:

代码语言:javascript
复制
#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的派生类都需要遵循,如:

代码语言:javascript
复制
QImage
QOpenGLPaintDevice
QPagedPaintDevice
QPaintDeviceWindow
QPicture
QPixmap

  君君在实际使用中Qt的某些类内用到QPaintDevice或其派生类也需要遵循,如:

代码语言:javascript
复制
QIcon
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-12-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Qt君 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 下面的代码会有什么问题呢?
  • 2. 为什么会这样呢?
  • 3. 修正后的代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档