-1

我正在用 Python 和 Qt 开发一个应用程序,我想澄清一些事情。以这个代码示例为例:

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()

当我运行我的代码时,我得到

"AttributeError: 'MainWindow' object has no attribute 'timer'"

但是我没有self.serial在课堂上到处调用这种错误。这两个实例有什么区别,我应该如何调用timer它才能在整个班级中访问它?

4

2 回答 2

2

你在onPortSettings设置之前打电话timer

    self.on_PortSettings() <-- here

    self.timer = QTimer(self)            
于 2013-03-14T15:25:08.267 回答
0

做这个:

def __init__(self, parent = None):
    self.timer = None

...

def on_PortSettings(self):
    self.serial.close()
    if self.timer is not None:
        self.timer.stop()
于 2013-03-14T15:27:12.590 回答