不建议修改设计文件,应创建另一个文件将逻辑与设计连接起来。因此,我假设设计文件名为ui_主窗口.py(
必须删除所有更改)
^{1}$
您的代码有点乱,所以我冒昧改进一下,在这种情况下,我将不使用QThread,而是使用qrunable的QThreadPool,为了发送信息,我将使用QMetaObject:
使用QThreadPool和{}
发送发票.py
^{pr2}$
我们将在主.py将创建小部件并建立连接的位置:
主.pyfrom 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_())
使用QThread
发送发票.pyfrom 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)
主.pyfrom 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_())