How do I update pyqt5 progress bar in Ui_MainWindow

雨燕双飞 提交于 2019-12-07 23:00:43

It is not recommended to modify the design file, it is appropriate to create another file to join the logic with the design. Therefore, I will assume that the design file is called ui_mainwindow.py( You must delete all changes)

.
├── main.py
├── sendInvoice.py
└── ui_mainwindow.py

Your code is a little messy so I take the liberty to improve it, in this case I will not use QThread, but QThreadPool with a QRunnable, and to send the information I will use the QMetaObject:

with QThreadPool and QRunnable

sendInvoice.py

from PyQt5 import QtCore

import requests
import json

class InvoiceRunnable(QtCore.QRunnable):
    def __init__(self, progressbar):
        QtCore.QRunnable.__init__(self)
        self.progressbar = progressbar

    def run(self):
        startInvNum = 100
        endInvNum = 102
        Username = 'test'
        Password = 'test'
        AccountNum = 'test'
        environmentURL = 'http://www.test.com/api?INV' ##remove this temporary


        headerData = { 
            'Authorization': 'auth_email={}, auth_signature={}, auth_account={}'.format(Username, Password, AccountNum),
            'content-type': 'application/json',
        }

        totalRequest = endInvNum - startInvNum + 1 

        for n, i in enumerate(range(startInvNum, endInvNum+1)):
            result = requests.get(environmentURL + str(i), headers=headerData)

            print (result.text)
            jsonOutput = json.loads(result.text)
            print(json.dumps(jsonOutput, sort_keys=True, indent=4))
            print(n+1, totalRequest)
            currentPercentage = (n+1)*100/totalRequest
            QtCore.QMetaObject.invokeMethod(self.progressbar, "setValue",
                                 QtCore.Qt.QueuedConnection,
                                 QtCore.Q_ARG(int, currentPercentage))

we will join both parts in the main.py where the widget will be created and make the connection:

main.py

from PyQt5 import QtCore, QtGui, QtWidgets
from ui_mainwindow import Ui_MainWindow
from sendInvoice import InvoiceRunnable

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.progressBar.setRange(0, 100)
        self.pushButton.clicked.connect(self.sendInvoice)

    def sendInvoice(self):
        runnable = InvoiceRunnable(self.progressBar)
        QtCore.QThreadPool.globalInstance().start(runnable)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

with QThread

sendInvoice.py

from PyQt5 import QtCore

import requests
import json

class InvoiceThread(QtCore.QThread):
    percentageChanged = QtCore.pyqtSignal(int)

    def run(self):
        startInvNum = 100
        endInvNum = 102
        Username = 'test'
        Password = 'test'
        AccountNum = 'test'
        environmentURL = 'http://www.test.com/api?INV' ##remove this temporary


        headerData = { 
            'Authorization': 'auth_email={}, auth_signature={}, auth_account={}'.format(Username, Password, AccountNum),
            'content-type': 'application/json',
        }

        totalRequest = endInvNum - startInvNum + 1 

        for n, i in enumerate(range(startInvNum, endInvNum+1)):
            result = requests.get(environmentURL + str(i), headers=headerData)

            print (result.text)
            jsonOutput = json.loads(result.text)
            print(json.dumps(jsonOutput, sort_keys=True, indent=4))
            print(n+1, totalRequest)
            currentPercentage = (n+1)*100/totalRequest
            self.percentageChanged.emit(currentPercentage)

main.py

from PyQt5 import QtCore, QtGui, QtWidgets
from ui_mainwindow import Ui_MainWindow
from sendInvoice import InvoiceThread

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.progressBar.setRange(0, 100)
        self.pushButton.clicked.connect(self.sendInvoice)

    def sendInvoice(self):
        thread = InvoiceThread(self)
        thread.percentageChanged.connect(self.progressBar.setValue)
        thread.start()


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!