为什么 QSplashscreen 并不总是有效? [英] Why QSplashscreen does not always work?

查看:83
本文介绍了为什么 QSplashscreen 并不总是有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在我的 PyQt 应用程序中编写了启动画面,以便在开始之前显示图像.我用过 QSplashscreen.问题是图像显示,比方说,每 20 次显示一次.在其他情况下,会显示一个灰色矩形.两种情况的截图:

I've just coded splash screen in my PyQt application, to show an image before start. I've used QSplashscreen. The problem is the image is displayed, let's say, once in a 20 times. In other cases there is a grey rectangle displayed istead. Screenshots of both cases:

是否有效:http://dl.getdropbox.com/u/1088961/prob2.jpg

不起作用:http://dl.getdropbox.com/u/1088961/prob1.jpg

我试图延迟启动窗口,但如果灰色矩形变成图片,它就在消失之前(即使我延迟了 10 秒).

I tried to delay starting window, but if grey rectangle changes into picture it is just before vanishing (even if I delay everything 10 seconds).

这是我的代码:

# -*- coding: utf-8 -*-
import sys
from time import time, sleep
from PyQt4.QtGui import QApplication, QSplashScreen, QPixmap

from gui.gui import MainWindow

def main():
    app = QApplication(sys.argv)
    start = time() 
    splash = QSplashScreen(QPixmap("aquaticon/images/splash_screen.jpg"))
    splash.show()
    if time() - start < 1:
        sleep(1)
    win = MainWindow()
    splash.finish(win)
    win.show()
    app.exec_()

if __name__ == "__main__":
    main()

我将 Debian Linux 与 Fluxbox 一起使用(但在 Gnome 中也是如此).

I'm using Debian Linux with Fluxbox (but it is the same in Gnome).

推荐答案

这是因为 sleep(1) 行.为了使 QSplashScreen 正常工作,应该有一个事件循环在运行.但是,sleep 是阻塞的.所以你不会在 sleep 完成之前(一整秒)进入 app.exec_()(事件循环)部分.那个灰色矩形"就是你在 QSplashScreen 甚至可以自己绘制之前输入 sleep 的情况.

It's because of the sleep(1) line. For QSplashScreen to work properly, there should be an event loop running. However, sleep is blocking. So you don't get to app.exec_() (event loop) part before sleep finishes (for a whole second). That 'gray rectangle' is the case where you enter sleep before QSplashScreen could even paint itself.

对于正常情况,您不会遇到此问题,因为您将在 Qt 中等待并且事件循环将运行.如果你想模拟"一个等待,睡眠一小段时间并强制 app.processEvents() 完成它的工作:

For the normal case, you won't have this problem because you'll be waiting within Qt and the event loop will be running. If you want to 'simulate' a wait, sleep for small intervals and force the app to do its job with .processEvents():

# -*- coding: utf-8 -*-
import sys
from time import time, sleep
from PyQt4.QtGui import QApplication, QSplashScreen, QPixmap

from gui.gui import MainWindow

def main():
    app = QApplication(sys.argv)
    start = time() 
    splash = QSplashScreen(QPixmap("aquaticon/images/splash_screen.jpg"))
    splash.show()
    while time() - start < 1:
        sleep(0.001)
        app.processEvents()
    win = MainWindow()
    splash.finish(win)
    win.show()
    app.exec_()

if __name__ == "__main__":
    main()

这篇关于为什么 QSplashscreen 并不总是有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆