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

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)

错误是“AttributeError:'botclass' 对象没有属性 'loglist'”

我在 Python 中使用 PyQt5 时遇到此错误,我该如何解决? “botclass”将与硒一起使用。

如何解决这个问题?

要解决此问题,您需要在与 botclass 相同的 class 中声明 loglist。 它将是:

class botclass(QtCore.QObject):
    def __init__(self):
        self.loglist = #what you want loglist to be
    progressChanged = QtCore.pyqtSignal(int)
    def bot(self):
        example_error_message = QListWidgetItem("Error")
        example_error_message.setForeground(Qt.red)
        self.loglist.insertItem(0, error)

如果 loglist 已经是 class 之前的变量,则执行此操作:

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

这使得self.loglist=到全局变量loglist

您不能从另一个线程访问 GUI,您必须做的是创建一个发送文本的信号,然后在 GUI 中创建项目:

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)