c++ - Qt : Display a picture during application loading

标签 c++ qt qml qpixmap qsplashscreen

我想为加载缓慢的应用程序添加启动画面。 我已经创建了一个简单的应用程序来测试。

main.cpp :

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QPixmap pixmap("/home/helene/Images/my_image.png");
    if (pixmap.isNull())
    {
        pixmap = QPixmap(300, 300);
        pixmap.fill(Qt::magenta);
    }

    QSplashScreen *splash = new QSplashScreen(pixmap);
    splash->show();
    splash->showMessage("Loaded modules dsjhj");

    QQmlApplicationEngine engine;
    engine.load(QUrl("qrc:/main.qml"));

    QObject *topLevel = engine.rootObjects().value(0);
    QQuickWindow *window = qobject_cast<QQuickWindow *>(topLevel);
    if ( !window )
    {
        qWarning("Error: Your root item has to be a Window.");
        return -1;
    }
    else
    {
        window->showFullScreen();
    }
    return app.exec();
}

主.qml

Window {
    visible: false
    width: 360
    height: 360

    property variant t: determineT()
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }

    function determineT() {
        for(var i=0; i<1000000000; i++);
    }
}

我添加了一个 long 函数来增加加载时间。 当应用程序状态时,我可以看到图片的“阴影”。图片似乎在应用程序之前完全加载。 我试过在资源上使用图像和绝对路径,但问题是一样的。 Picture of the "shadow"

最佳答案

通常 QSplashScreen 在显示主窗口之前使用,在此期间您要执行一些初始化任务。由于闪屏是在事件循环开始之前显示的,因此您应该定期调用 QApplication::processEvents() 来处理与闪屏相关的事件:

QSplashScreen splash(pixmap);
splash.show();
qApp->processEvents(QEventLoop::AllEvents);

//Initialization
...

qApp->processEvents(QEventLoop::AllEvents);

//Initialization
...

在您的情况下,您正在显示启动画面并立即加载进入长循环的 qml 文件,因此不会处理启动画面事件。在显示初始屏幕后和加载 qml 文件之前尝试此操作:

qApp->processEvents(QEventLoop::AllEvents);

关于c++ - Qt : Display a picture during application loading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28028887/

相关文章:

c++ - Boost三次Hermite插值 "requires template argument list"

c++ - 如果 bug 没有持续明显地出现,如何查看它是否仍然存在?

python - 带有 QML 和 PyQt 的项目列表

qt - 在 Qt5 中使用文本元素的彩色点

c++ - 如何将 boost::geometry::rtree 与 glm::vec3 一起用作自定义点类型?

c++ - "Declaration of xxx outside of class is not definition"错误

c++ - 如何在不使用 C++0x auto 的情况下实现这种类型特定的对象生成器

qt - 从QWebEngineView或QWebEnginePage删除ScrollBar

c++ - QWidget::layout() 不能返回 QGridLayout?

c++ - 用于 mingw 的 msi.h