1
我爲我的問題寫了一個示例代碼。此代碼應產生兩個給定數字的和,並在文本瀏覽器中顯示結果,然後用sum替換第一個數字,並將其添加到第二個數字並再次在文本瀏覽器中顯示結果。此過程應繼續。問題是:使用Qthread時Signal-Slot的問題
1 - 爲什麼信號無法正常工作?
2 - 我怎樣才能發出信號與總數顯示文本瀏覽器?
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class AreaThread(QThread):
signal = pyqtSignal()
def __init__(self, no1, no2, parent):
QThread.__init__(self)
self.no1 = no1
self.no2 = no2
def area(self):
for i in range(10):
self.sum = self.no1 + self.no2
self.no1 = self.no2
self.no2 = self.sum
self.signalemit()
time.sleep(1)
def signalemit(self):
self.signal.emit()
def run(self):
self.area()
class GeneralizedRun (QMainWindow):
def __init__(self, no1, no2):
QMainWindow.__init__(self)
self.no1 = no1
self.no2 = no2
def initUi(self, mainwindow):
mainwindow.centralWidget = QWidget(mainwindow)
self.runflow = QTextBrowser()
self.runflow.isReadOnly()
self.runflow.setText('running:')
self.runflow.moveCursor(QTextCursor.End)
self.runflow.show()
mainwindow.centralWidget = self.runflow
self.threadruning()
def threadruning(self):
self.area = AreaThread(self.no1, self.no2, self)
self.area.start()
self.area.signal.connect(self.updatetexteditor)
def updatetexteditor(self):
self.runflow.insertPlainText('\n\n' + 'sum')
self.runflow.moveCursor(QTextCursor.End)
class MainApplication(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle('Home')
self.setGeometry(50, 50, 500, 500)
#Main widget
self.mainwidget = QWidget()
self.mainlayout = QVBoxLayout()
#Widgets
#Form line edits
self.no1 = QLineEdit()
self.no2 = QLineEdit()
self.run = QPushButton('Run')
self.exit = QPushButton('Exit')
self.form = QFormLayout()
self.form.addRow('First number', self.no1)
self.form.addRow('Second number', self.no2)
self.mainlayout.addLayout(self.form)
self.mainlayout.addWidget(self.run)
self.mainlayout.addWidget(self.exit)
self.exit.clicked.connect(self.exitapplication)
self.run.clicked.connect(self.mainprogramrun)
self.mainwidget.setLayout(self.mainlayout)
self.mainwidget.show()
def exitapplication(self):
sys.exit()
def mainprogramrun(self):
number1 = float(self.no1.text())
number2 = float(self.no2.text())
run = GeneralizedRun(number1, number2)
run.initUi(self)
def main():
application = QApplication(sys.argv)
application_window = MainApplication()
application.exec_()
if __name__ == '__main__':
main()
'self.process.signal.connect(self.updatetexitor)'。 – ekhumoro
我在這裏輸入的錯誤。我修好了,仍然不起作用。 –
在你真實的代碼中調用'initUi()'是否有任何東西?如果這不是問題,請閱讀關於如何製作[mcve]的指導。 – ekhumoro