問題描述
我構建了一個 PyQt5 GUI 來進行一些 Selenium 測試.一切都按預期工作,除了 PyQt 進度條.
I built a PyQt5 GUI to do some Selenium testing. Everything works as expected, except for the PyQt progress bar.
在下面的第一個示例中,我使用 Selenium 瀏覽器,最后,當瀏覽器關閉時,進度條會跳轉到 100%.但是,Selenium 按預期工作.
In the first example below, where I use the Selenium browser, the progress bar just jumps to 100%, at the end, when the browser closes. But, the Selenium works as expected.
def test(self):
self.completed = 0
browser = webdriver.Firefox()
links = ['http://www.somesite.com/', 'http://www.somesite.com/page2',
'http://www.somesite.com/page3']
for link in links:
browser.get(link)
self.completed += 100 / len(links)
time.sleep(2)
print(link)
self.progressBar.setValue(self.completed)
browser.close()
但是,在下面的這個版本中,在注釋掉 Selenium 瀏覽器的情況下,進度條按預期工作.
But, in this version below, with the Selenium browser commented out, the progress bar works as expected.
def test(self):
self.completed = 0
#browser = webdriver.Firefox()
links = ['http://www.somesite.com/', 'http://www.somesite.com/page2',
'http://www.somesite.com/page3']
for link in links:
#browser.get(link)
self.completed += 100 / len(links)
time.sleep(2)
print(link)
self.progressBar.setValue(self.completed)
#browser.close()
推薦答案
阻塞任務對執行 GUI 的事件循環不友好,因為它們阻止了 GUI 執行的正常任務,例如票證檢查、重繪等. 從被處決.
The blocking tasks are not friendly with the event loop where the GUI is executed as they prevent the normal tasks that the GUI performs such as ticket checking, redrawing, etc. from being executed.
在這些情況下的解決方案是使用線程執行阻塞任務并使用信號發送信息.
The solution in these cases is to use thread to execute the blocking task and use the signals to send the information.
import sys
from PyQt5 import QtCore, QtWidgets
from selenium import webdriver
class SeleniumWorker(QtCore.QObject):
progressChanged = QtCore.pyqtSignal(int)
def doWork(self):
progress = 0
browser = webdriver.Firefox()
links = ['http://www.somesite.com/',
'http://www.somesite.com/page2',
'http://www.somesite.com/page3']
for link in links:
browser.get(link)
progress += 100 / len(links)
self.progressChanged.emit(progress)
browser.close()
class Widget(QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QWidget.__init__(self, *args, **kwargs)
lay = QtWidgets.QHBoxLayout(self)
progressBar = QtWidgets.QProgressBar()
progressBar.setRange(0, 100)
button = QtWidgets.QPushButton("Start")
lay.addWidget(progressBar)
lay.addWidget(button)
self.thread = QtCore.QThread()
self.worker = SeleniumWorker()
self.worker.moveToThread(self.thread)
self.thread.started.connect(self.worker.doWork)
button.clicked.connect(self.thread.start)
self.worker.progressChanged.connect(progressBar.setValue, QtCore.Qt.QueuedConnection)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
這篇關于當我將 PyQt QProgressBar 與 Selenuim 一起使用時,它不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!