pythonpyqt5qlistwidget

AttributeError: 'botclass' object has no attribute 'loglist'


class botclass(QtCore.QObject):
    progressChanged = QtCore.pyqtSignal(int)
    def bot(self):
        example_error_message = QListWidgetItem("Error")
            example_error_message.setForeground(Qt.red)
            self.loglist.insertItem(0, error)



class MainPage(QMainWindow):
        def __init__(self, *args, **kwargs):
            QtWidgets.QWidget.__init__(self, *args, **kwargs)
            loadUi("uifile.ui", self)
            example_working_message = QListWidgetItem("Working")
            example_working_message.setForeground(Qt.green)
            self.loglist.insertItem(0, example_working_message)


            self.thread = QtCore.QThread()
            self.botwork = botclass()
            self.botwork.moveToThread(self.thread)
            self.thread.started.connect(self.botwork.bot)
            self.botwork.clicked.connect(self.thread.start)

Error is "AttributeError: 'botclass' object has no attribute 'loglist'"

I'm getting this error when using PyQt5 in Python, how can I solve it? "botclass" will be used with selenium.

How can fix this?


Solution

  • You must not access the GUI from another thread, what you must do is create a signal that sends the text and then in the GUI you create the item:

    class BotClass(QtCore.QObject):
        progressChanged = QtCore.pyqtSignal(int)
        messageChanged = QtCore.pyqtSignal(str)
    
        def bot(self):
            self.messageChanged.emit("Error")
    
    
    class MainPage(QMainWindow):
        def __init__(self, *args, **kwargs):
            QtWidgets.QMainWindow.__init__(self, *args, **kwargs)
            loadUi("uifile.ui", self)
    
            self.add_item("Working", Qt.green)
    
            self.bot_thread = QtCore.QThread()
            self.botwork = BotClass()
            self.botwork.messageChanged.connect(self.handle_message_changed)
            self.botwork.moveToThread(self.bot_thread)
            self.bot_thread.started.connect(self.botwork.bot)
            self.<some_button>.clicked.connect(self.bot_thread.start)
            
        def handle_message_changed(self, message):
            self.add_item(message, Qt.red)
    
        def add_item(self, message, color):
            item = QListWidgetItem(message)
            item.setForeground(color)
            self.loglist.insertItem(0, item)