I'm new on PyQt and i just want to do QThreading. But i'm getting error : AttributeError: 'myThread' object has no attribute 'ui'
My code:
from time import sleep
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from takipSistemi import Ui_MainWindow
class anaPencere(QMainWindow):
def __init__(self):
QWidget.__init__(self)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
self.thread = myThread()
self.ui.tableWidget.setItem(0, 0, QTableWidgetItem("hi!"))
self.thread.start()
class myThread(QThread):
def __init__(self,parent=None):
QThread.__init__(self,parent)
self.exiting = False
def __del__(self):
self.exiting = True
self.wait()
def run(self):
#error
self.ui.tableWidget.setItem(0 , 0, QTableWidgetItem('hi there!'))
uyg=QApplication([])
pencere=anaPencere()
pencere.show()
uyg.exec_()
How can i attribute ui to myThread?
Of the two classes anaPencere
and myThread
only the first one has the attribute self.ui = ...
assigned. Because myThread
has no attribute ui
you get the error when calling self.ui.tableWidget...
.
To fix this you have several options. One would be to pass a reference of the class anaPencere
to its thread class:
class anaPencere(QMainWindow):
def __init__(self):
QWidget.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.thread = myThread(self)
self.ui.tableWidget.setItem(0, 0, QTableWidgetItem("hi!"))
self.thread.start()
class myThread(QThread):
def __init__(self,parent=None):
QThread.__init__(self, parent)
self.exiting = False
def __del__(self):
self.exiting = True
self.wait()
def run(self):
self.parent().ui.tableWidget.setItem(0 , 0, QTableWidgetItem('hi there!'))
If this approach (using anaPencere
as the parent
of QThread
) you could also pass self
as a second argument in myThread
's __init__
.
On a second note: you nearly always want to pass a parent object to each new created object that derives from Qt's QObject
(see here: https://stackoverflow.com/a/30354276/6205205)