問題描述
鑒于此,我從 PyQt5 模塊開始,我仍然在慢慢理解它背后的邏輯.也就是說,我遇到了一個無法找到答案的問題,希望您能幫助我.
我有這個腳本:
given that, I'm starting with the PyQt5 module, I'm still slowly understanding the logic behind it. That said, I'm having a problem that I can not find an answer to and I hope you can help me.
I have this script:
import sys, socket, time
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from io import BytesIO as by
class loadGame(QWidget):
wLoadDisplay = 768
hLoadDisplay = 576
wLoadBar = 650
hLoadBar = 40
pbarCSS = """
QProgressBar
{
font-size: 20px;
font-weight: bold;
background-color: #FFF;
border: 4px solid #000;
text-align: center;
}
QProgressBar::chunk
{
background-color: #FF0000;
width: 1px;
}
"""
labelCSS = """
QLabel
{
font-size: 20px;
font-weight: bold;
background-color: #FFF;
border: 4px solid #000;
}
"""
fileResource = []
imgResource = []
vidResource = []
audResource = []
diaResource = []
txtResource = []
internetConnection = False
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
self.outputFile = by()
self.pbar = QProgressBar(self)
self.pbar.setGeometry((self.wLoadDisplay / 2 - self.wLoadBar / 2), (self.hLoadDisplay / 2 - self.hLoadBar * 2),
self.wLoadBar, self.hLoadBar)
self.pbar.setFormat("%v/%m")
self.pbar.setValue(0)
self.pbar.setStyleSheet(self.pbarCSS)
self.label = QLabel(self)
self.label.setGeometry((self.wLoadDisplay / 2 - self.wLoadBar / 2), (self.hLoadDisplay / 2),
self.wLoadBar, self.hLoadBar)
self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
self.label.setStyleSheet(self.labelCSS)
self.setGeometry(0, 0, self.wLoadDisplay, self.hLoadDisplay)
oImage = QImage("bgloading.png")
sImage = oImage.scaled(QSize(self.wLoadDisplay, self.hLoadDisplay))
palette = QPalette()
palette.setBrush(10, QBrush(sImage))
self.setPalette(palette)
qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())
self.run()
def run(self):
self.checkConnection()
if self.internetConnection:
self.checkUpdate()
else:
pass
def checkConnection(self):
self.objectChange("Check Internet Connection", 1)
try:
host = socket.gethostbyname("www.google.it")
s = socket.create_connection((host, 80), 2)
self.internetConnection = True
except:
pass
self.count()
self.reset()
def checkUpdate(self):
pass
def objectChange(self, object, n):
self.label.setText(object)
self.pbar.setMaximum(n)
def count(self):
self.pbar.setValue(self.pbar.value() + 1)
def reset(self):
time.sleep(2)
self.pbar.setMaximum(0)
self.pbar.setValue(0)
self.label.setText("...")
if __name__ == '__main__':
loadDisplay = QApplication(sys.argv)
load = loadGame()
load.show()
sys.exit(loadDisplay.exec_())
在網上搜索,發現問題與time.sleep(2)"有關,即指令阻塞了兩秒后才出現的窗口.
事實是,我想花一兩秒鐘,顯示完成欄,然后再重置并繼續執行def run (self)"中包含的下一條語句.
那么,有沒有辦法在不使用 Time 模塊的情況下暫停?我不知道,也許用QTimer?我再說一遍,我對 PyQt5 還不太了解,所以我不知道 QTimer 是否可以做同樣的事情.
如果 QTimer 做不到,是否可以通過其他方式實現?我想避免使用 PyQt5 的線程",因為我讀到有可能做到這一點,但我想避免僅將它用于 Timer 模塊.
我只添加了一個問題,以避免打開另一個問題并發布相同的腳本.
在腳本中,窗口背景是通過 "oImage = QImage (" bgloading.png ")" 等完成的.
但是,我注意到,如果發現文件名錯誤,或者文件本身丟失,則背景為黑色.因此,如果有任何錯誤(名稱錯誤或文件丟失),是否可以設置背景,例如白色?
因為當窗口加載此錯誤"時,不會引發異常,腳本會繼續執行.
我編輯了已發布的腳本,使其僅包含 PyQt5 部分,因此您可以嘗試一下.顯然只有圖片丟失了,可以用任意圖片替換.
不幸的是我忘記寫報告self.set_display()"的部分是表明一旦PyQt5執行的工作被終止,它將被關閉(仍然丟失,因為使用Pycharm我會關閉執行程序中的腳本).腳本將通過調用self.set_display()"函數繼續.
Searching on the web, I discovered that the problem is related to "time.sleep (2)", that is, the instruction blocks the window that does not appear until two seconds have passed.
The fact is that I would like to spend one or two seconds, showing the completion of the bar, before resetting and move on to the next statement contained in "def run (self)".
So, is there a way to make that pause, without using the Time module? I do not know, maybe with QTimer? I repeat, I do not know much about PyQt5 yet, so I'm not aware if QTimer can do the same thing.
If QTimer can not do it, is it possible in any other way? I would like to avoid the "threads" of PyQt5, because I read that it would be possible to do it, but I would like to avoid using it only for the Timer module.
I only add one more question, to avoid opening another one and publishing the same script.
In the script, the window background is done via "oImage = QImage (" bgloading.png ")" etc.
I noticed, however, that if the file name were found to be wrong, or the file itself is missing, the background is colored black. So, if there are any errors (wrong name or missing file) it's possible set a background, for example, white?
Because when the window is loaded with "this error", no exception is raised and the script continues.
I've edited the published script so that it contains only the PyQt5 part, so you can try it out. Obviously only the image is missing, which can be replaced with any image.
Unfortunately I had forgotten to write that the part where "self.set_display ()" was reported was to show that once the work performed by PyQt5 was terminated, it would be closed (which was still missing, because using Pycharm I would close the execution of the script from the program). The script would continue by calling the "self.set_display ()" function.
Edit2:按照建議,我嘗試替換time.sleep (2)",但得到了相同的結果.問題是,如果我不暫停,窗口會正常顯示,但重置發生得太快,用戶看不到進度條的填充.如果我改為輸入time.sleep (2)",或者建議的解決方案,窗口僅在暫停后出現,即重置已經發生.
I tried, as suggested, to replace "time.sleep (2)", but I get the same result. The problem is that if I do not put the pause, the window appears normally, but the reset happens too quickly and the user does not see the filling of the progress bar. If instead I put "time.sleep (2)" or, the suggested solution, the window appears only after the pause, that is when the reset has already occurred.
推薦答案
對PyQt友好的等價于time.sleep(2)
的表達式如下:
An expression equivalent to time.sleep(2)
that is friendly to PyQt is as follows:
loop = QEventLoop()
QTimer.singleShot(2000, loop.quit)
loop.exec_()
<小時>
問題是因為你在暫停后顯示小部件,你必須在調用run()
之前做,另外一個錯誤是使用QImage
,因為您必須使用 QPixmap
的小部件問題.
The problem is caused because you are showing the widget after the pause, you must do it before calling run()
, Also another error is to use QImage
, for questions of widgets you must use QPixmap
.
如果文件不存在,那么 QPixmap
將為空,要知道它是否存在,您應該使用 isNull()
方法:
If the file does not exist then QPixmap
will be null and to know if it is you should use the isNull()
method:
[...]
self.setGeometry(0, 0, self.wLoadDisplay, self.hLoadDisplay)
palette = self.palette()
pixmap = QPixmap("bgloading.png")
if not pixmap.isNull():
pixmap = pixmap.scaled(QSize(self.wLoadDisplay, self.hLoadDisplay))
palette.setBrush(QPalette.Window, QBrush(pixmap))
else:
palette.setBrush(QPalette.Window, QBrush(Qt.white))
self.setPalette(palette)
qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())
self.show()
self.run()
[...]
def reset(self):
loop = QEventLoop()
QTimer.singleShot(2000, loop.quit)
loop.exec_()
self.pbar.setMaximum(0)
self.pbar.setValue(0)
self.label.setText("...")
這篇關于time.sleep() 和背景 Windows PyQt5的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!