2021年4月30日星期五

How to access self object within class from outside

I am writing an application that uses a Qt GUI and am now trying to multithread it (first time learner). A longer task will be contained within the worker thread eventually but output logs will be required to be written as it goes. The GUI class has a method to output these logs to a plain text widget. Up until now, everything has been running within the GUI class.

I currently have the following code (included the important bits for brevity):

class Worker(QRunnable):      @pyqtSlot()      def run(self):          Ui.logentry(self, "Test")        class Ui(QtWidgets.QMainWindow):      def __init__(self):          super(Ui, self).__init__()          uic.loadUi(resourcepath('./pycdra.ui'), self)                    self.outputlog = self.findChild(QtWidgets.QPlainTextEdit, 'outputlog')          self.button = self.findChild(QtWidgets.QPushButton, 'button')          self.button.clicked.connect(self.Button)          self.threadpool = QThreadPool()          self.logentry("Available threads: %d" % self.threadpool.maxThreadCount())                def Button(self):          worker = Worker()          self.threadpool.start(worker)            def logentry(self, returntext):          self.outputlog.appendPlainText(self.timestamp() + " " + str(returntext))          self.outputlog.repaint()                def timestamp(self):          import datetime          ts = datetime.datetime.now(tz=None.strftime("%Y-%m-%d %H:%M:%S"))          return ts            def applic():      app = QApplication(sys.argv)      window = Ui()      window.show()      sys.exit(app.exec_())    applic()  

When I try running this, the GUI loads perfectly, but upon pushing button the Ui.logentry part of Worker returns the error: AttributeError: 'Worker' object has no attribute 'outputlog'

I attempted making logentry() and timestamp() global so they can access and be accessed by both classes, but the closest I got with the line Ui.self.outputlog.appendPlainText(self.timestamp() + " " + str(returntext)) was that 'Ui' object has no attribute 'self'.

What am I missing? Am I right in making them global or are there other means to do this?

https://stackoverflow.com/questions/67342411/how-to-access-self-object-within-class-from-outside May 01, 2021 at 10:34AM

没有评论:

发表评论