I'm developping an application in Python and Qt and there is something that I'd like to clarify. Take this code example:
import serial
from PySide.QtGui import QMainWindow
from PySide import QtCore, QtGui
from PySide.QtCore import QTimer
from ZumaUI import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
'''
MainWindow: this is the class that manages all the functionality.
'''
def __init__(self, parent = None):
'''
Default Constructor. It can receive a top window as parent.
'''
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.serial = serial.Serial()
self.serial.port = 'COM1'
self.serial.baudrate = 19200
self.serial.timeout = 0.5 #make sure that the alive event can be checked from time to time
self.on_PortSettings()
self.timer = QTimer(self)
self.timer.timeout.connect(self.OnRefresh)
self.timer.start(150)
self.on_PortSettings()
def OnRefresh(self):
pass
def on_PortSettings(self):
self.serial.close()
self.timer.stop()
When I run my code, I get
"AttributeError: 'MainWindow' object has no attribute 'timer'"
But I don't have this kind of error for self.serial
which is called all over within the class. What is the difference between these two instances and how should I call timer
so it can be accessed throughout the class?
You're calling onPortSettings
before you set up timer
.
self.on_PortSettings() <-- here
self.timer = QTimer(self)