简体   繁体   中英

PyQt5 Access GUI elements from QThread

Im trying to access GUI Elements from a QThread, but without success so far. im using this example because i want to find an easy and clean way to access the elements, help?

class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()


        uic.loadUi("GUI.ui", self)
        self.thread = {}

        self.listbox_devices = self.findChild(QListWidget, "listbox_devices")

        self.btn_start = self.findChild(QPushButton, "btn_start")
        self.btn_start.clicked.connect(self.Worker_Registration)

   def Worker_Registration(self):
    self.thread = ThreadClass(parent=None)
    self.thread.start()


class ThreadClass(QtCore.QThread):

    any_signal = QtCore.pyqtSignal(int)

    def __init__(self,parent=None):
        super(ThreadClass, self).__init__(parent)

        self.is_running = True
    def run(self):
        devices = UI.listbox_devices.count()
        if not devices > 0: UI.textbox_log.append("No Device Connected"); return

app = QApplication(sys.argv)
UIWindow = UI()
UIWindow.show()
app.exec_()

I get this error:

    py", line 149, in run
    devices = UI.listbox_devices.count()
AttributeError: type object 'UI' has no attribute 'listbox_devices'

I think you could pass the class UI itself

class UI(QMainWindow):
    def __init__(self):
        super(UI, self).__init__()


        uic.loadUi("GUI.ui", self)
        self.thread = {}

        self.listbox_devices = self.findChild(QListWidget, "listbox_devices")

        self.btn_start = self.findChild(QPushButton, "btn_start")
        self.btn_start.clicked.connect(self.Worker_Registration)

   def Worker_Registration(self):
    self.thread = ThreadClass(self, parent=None)
    self.thread.start()


class ThreadClass(QtCore.QThread):

    any_signal = QtCore.pyqtSignal(int)

    def __init__(self, ui, parent=None):
        super(ThreadClass, self).__init__(parent)
        self.ui = ui

        self.is_running = True
    def run(self):
        devices = self.ui.listbox_devices.count()
        if not self.number_devices > 0: self.ui.textbox_log.append("No Device Connected"); return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM