问题
I want to insert text items from a Worker Qthread to a QTableWidget UI in Main thread ?.
I want to know the Syntax to create the signal in Main thread , so I can insert the text as well as the row and column from Worker thread by sending via signal
class Example(QWidget):
def __init__(self):
super().__init__()
self.myclass2 = myclass2()
self.myclass2.start()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
self.show()
class myclass2(QThread):
def __init__(self, parent=None):
super(myclass2, self).__init__(parent)
def run(self):
while True:
time.sleep(.1)
print(" in thread \n")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
回答1:
You already know that you must use a signal, now the question is: what data do you need to send?, You can think that you should send the row, the column and the text, so the signal must send 2 whole and one string, then you connect it to a slot and in it you insert it as if the data was created in the main thread:
import sys
import time
import random
from PyQt5 import QtCore, QtWidgets
class Example(QtWidgets.QWidget):
def __init__(self):
super().__init__()
lay = QtWidgets.QVBoxLayout(self)
self.table = QtWidgets.QTableWidget(10, 10)
lay.addWidget(self.table)
self.myclass2 = myclass2()
self.myclass2.new_signal.connect(self.some_function)
self.myclass2.start()
@QtCore.pyqtSlot(int, int, str)
def some_function(self, r, c, text):
it = self.table.item(r, c)
if it:
it.setText(text)
else:
it = QtWidgets.QTableWidgetItem(text)
self.table.setItem(r, c, it)
class myclass2(QtCore.QThread):
new_signal = QtCore.pyqtSignal(int, int, str)
def run(self):
while True:
time.sleep(.1)
r = random.randint(0, 9)
c = random.randint(0, 9)
text = "some_text: {}".format(random.randint(0, 9))
self.new_signal.emit(r, c, text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Example()
ex.showMaximized()
sys.exit(app.exec_())
来源:https://stackoverflow.com/questions/52308937/python-qt-how-to-insert-items-in-table-widget-from-another-thread