Python Qt - 如何从另一个线程在表小部件中插入项目? [英] Python Qt - How to insert items in Table widget from another Thread?

查看:63
本文介绍了Python Qt - 如何从另一个线程在表小部件中插入项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Worker Qthread 中的文本项插入到主线程中的 QTableWidget UI 中?.

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

推荐答案

你已经知道必须使用信号,现在的问题是:你需要发送什么数据?,你可以认为您应该发送行,列和文本,因此信号必须发送 2 个完整的字符串和一个字符串,然后将其连接到一个插槽并在其中插入它,就好像数据是在主线程中创建的一样:

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

这篇关于Python Qt - 如何从另一个线程在表小部件中插入项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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