如何在 Ui_MainWindow 中更新 pyqt5 进度条 [英] How do I update pyqt5 progress bar in Ui_MainWindow

查看:78
本文介绍了如何在 Ui_MainWindow 中更新 pyqt5 进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 pyqt5 使进度条实时更新,但是,目前在线文档似乎非常有限.我在网上读到我可以使用线程和信号来做到这一点.但是,pyqt5 中的语法似乎发生了变化.这里有专家可以帮忙吗?

主界面窗口.

# -*- 编码:utf-8 -*-## 创建者:PyQt5 UI 代码生成器 5.9## 警告!在此文件中所做的所有更改都将丢失!从 PyQt5 导入 QtCore、QtGui、QtWidgets从 sendInvoice 导入 *类 Ui_MainWindow(对象):def setupUi(self, MainWindow):MainWindow.setObjectName("MainWindow")MainWindow.resize(441, 175)self.centralwidget = QtWidgets.QWidget(MainWindow)self.centralwidget.setObjectName("centralwidget")self.progressBar = QtWidgets.QProgressBar(self.centralwidget)self.progressBar.setGeometry(QtCore.QRect(30, 20, 411, 61))self.progressBar.setProperty("value", 0)self.progressBar.setObjectName("progressBar")self.pushButton = QtWidgets.QPushButton(self.centralwidget)self.pushButton.setGeometry(QtCore.QRect(160, 100, 75, 23))self.pushButton.setObjectName("pushButton")MainWindow.setCentralWidget(self.centralwidget)self.menubar = QtWidgets.QMenuBar(MainWindow)self.menubar.setGeometry(QtCore.QRect(0, 0, 441, 21))self.menubar.setObjectName("menubar")MainWindow.setMenuBar(self.menubar)self.statusbar = QtWidgets.QStatusBar(MainWindow)self.statusbar.setObjectName("statusbar")MainWindow.setStatusBar(self.statusbar)self.retranslateUi(MainWindow)self.pushButton.clicked.connect(self.sendInvoice)QtCore.QMetaObject.connectSlotsByName(MainWindow)def retranslateUi(self, MainWindow):_translate = QtCore.QCoreApplication.translateMainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))self.pushButton.setText(_translate("MainWindow", "Send"))def sendInvoice(self):sendInvoice.sendInv()如果 __name__ == "__main__":导入系统app = QtWidgets.QApplication(sys.argv)MainWindow = QtWidgets.QMainWindow()ui = Ui_MainWindow()ui.setupUi(主窗口)MainWindow.show()sys.exit(app.exec_())

发送发票的工人文件.

导入请求导入json导入系统从 PyQt5.QtWidgets 导入(QWidget、QProgressBar、QPushButton、QApplication)类发送发票():def sendInv(self):startInvNum = int(100)endInvNum = int(102)用户名 = '测试'密码 = '测试'AccountNum = 测试environmentURL = 'http://www.test.com/api?INV' ##删除这个临时的totalRequest = int(endInvNum) - int(startInvNum)n = 1标头数据 = {'授权': 'auth_email=' + 用户名 + ', auth_signature=' + 密码 + ', auth_account=' + AccountNum,'内容类型':'应用程序/json',}QApplication.processEvents()对于范围内的 i(startInvNum, endInvNum+1):结果 = requests.get(environmentURL + str(i), headers=headerData)打印(结果.文本)jsonOutput = json.loads(result.text)打印 (json.dumps(jsonOutput, sort_keys=True, indent=4))self.currentCount = str(n)self.total = str(totalRequest)百分比 = sendInvoice.getPercentage(self)印刷(百分比)QApplication.processEvents()n += 1def getPercentage(self):count = int(self.currentCount)总计 = int(self.total)currentPercentage = (count/(total + 1) * 100)打印(当前百分比 * 100)返回当前百分比

解决方案

不建议修改设计文件,创建另一个文件将逻辑与设计连接起来是合适的.因此,我假设设计文件名为 ui_mainwindow.py(您必须删除所有更改)

<预><代码>.├── main.py├── sendInvoice.py└── ui_mainwindow.py

你的代码有点乱所以我冒昧改进一下,在这种情况下我不会使用QThread,而是使用带有QRunnable的QThreadPool,并且发送信息我将使用QMetaObject:

带有 QThreadPoolQRunnable

sendInvoice.py

from PyQt5 import QtCore进口请求导入json类 InvoiceRunnable(QtCore.QRunnable):def __init__(self,progressbar):QtCore.QRunnable.__init__(self)self.progressbar = 进度条定义运行(自我):startInvNum = 100endInvNum = 102用户名 = '测试'密码 = '测试'AccountNum = '测试'environmentURL = 'http://www.test.com/api?INV' ##删除这个临时的标头数据 = {'授权': 'auth_email={}, auth_signature={}, auth_account={}'.format(Username, Password, AccountNum),'内容类型':'应用程序/json',}totalRequest = endInvNum - startInvNum + 1对于 n, i in enumerate(range(startInvNum, endInvNum+1)):结果 = requests.get(environmentURL + str(i), headers=headerData)打印(结果.文本)jsonOutput = json.loads(result.text)打印(json.dumps(jsonOutput,sort_keys=True,缩进=4))打印(n+1,总请求)currentPercentage = (n+1)*100/totalRequestQtCore.QMetaObject.invokeMethod(self.progressbar, "setValue",QtCore.Qt.QueuedConnection,QtCore.Q_ARG(int, currentPercentage))

我们将在将创建小部件的 main.py 中加入这两个部分并建立连接:

ma​​in.py

from PyQt5 import QtCore, QtGui, QtWidgets从 ui_mainwindow 导入 Ui_MainWindow从 sendInvoice 导入 InvoiceRunnable类 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)如果 __name__ == "__main__":导入系统app = QtWidgets.QApplication(sys.argv)w = 主窗口()w.show()sys.exit(app.exec_())

使用 QThread

sendInvoice.py

from PyQt5 import QtCore进口请求导入json类发票线程(QtCore.QThread):百分比变化 = QtCore.pyqtSignal(int)定义运行(自我):startInvNum = 100endInvNum = 102用户名 = '测试'密码 = '测试'AccountNum = '测试'environmentURL = 'http://www.test.com/api?INV' ##删除这个临时的标头数据 = {'授权': 'auth_email={}, auth_signature={}, auth_account={}'.format(Username, Password, AccountNum),'内容类型':'应用程序/json',}totalRequest = endInvNum - startInvNum + 1对于 n, i in enumerate(range(startInvNum, endInvNum+1)):结果 = requests.get(environmentURL + str(i), headers=headerData)打印(结果.文本)jsonOutput = json.loads(result.text)打印(json.dumps(jsonOutput,sort_keys=True,缩进=4))打印(n+1,总请求)currentPercentage = (n+1)*100/totalRequestself.percentageChanged.emit(currentPercentage)

ma​​in.py

from PyQt5 import QtCore, QtGui, QtWidgets从 ui_mainwindow 导入 Ui_MainWindow从 sendInvoice 导入 InvoiceThread类 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.percentageChanged.connect(self.progressBar.setValue)线程开始()如果 __name__ == "__main__":导入系统app = QtWidgets.QApplication(sys.argv)w = 主窗口()w.show()sys.exit(app.exec_())

I try to make the progress bar update real-time with pyqt5, however, the documentation online seems very limited for now. I read online that I can use thread and signal to do that. However, the syntax seems changed in pyqt5. Can any experts here help?

Main ui window.

# -*- coding: utf-8 -*-
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from sendInvoice import *

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(441, 175)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
        self.progressBar.setGeometry(QtCore.QRect(30, 20, 411, 61))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(160, 100, 75, 23))
        self.pushButton.setObjectName("pushButton")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 441, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.pushButton.clicked.connect(self.sendInvoice)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Send"))

    def sendInvoice(self):
        sendInvoice.sendInv()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

worker file where the invoice is sending out.

import requests
import json
import sys

from PyQt5.QtWidgets import (QWidget, QProgressBar, QPushButton, QApplication)





class sendInvoice():

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


        n = 1

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

        QApplication.processEvents()


        for i in 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))
            self.currentCount = str(n)
            self.total = str(totalRequest)
            percentage = sendInvoice.getPercentage(self)
            print (percentage)
            QApplication.processEvents()
            n += 1

    def getPercentage(self):

        count = int(self.currentCount)
        total = int(self.total)
        currentPercentage = (count / (total + 1) * 100)
        print(currentPercentage * 100)
        return currentPercentage

解决方案

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_())

这篇关于如何在 Ui_MainWindow 中更新 pyqt5 进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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