无法连接在qt类之外导入的函数

时间:2015-11-08 17:04:44

标签: python qt class python-import

我有一个很大的功能(600多行),为了便于阅读,我不想从主代码中删除,但是,我无法在主窗口类中引用该功能。如果我将import语句移到类中,它可以无缝地工作,但我打算在别处使用它,所以不想多次导入它。有没有一种简单的方法可以在窗口中引用导入的函数?

import sys
import cv2
from PySide import QtCore
from PySide import QtGui
import mainWindowUI
from videoFunctions import videoFeed

class MainWindow(QtGui.QMainWindow, mainWindowUI.Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setup_camera()

    def setup_camera(self):
        self.capture = cv2.VideoCapture(0)      
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.videoFeed)
        self.timer.start(30)

app = QtGui.QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()

回溯:

File "<stdin>", line 1, in <module>
File "C:\WinPython\python-2.7.10.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 790, in runfile
  execfile(filename, namespace)
File "C:\WinPython\python-2.7.10.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 77, in execfile
  exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Scanner.py", line 42, in <module>
form = MainWindow()
File "C:/Scanner.py", line 17, in __init__
self.setup_camera()
File "C:/Scanner.py", line 37, in setup_camera
self.timer.timeout.connect(self.videoFeed)
AttributeError: 'MainWindow' object has no attribute 'videoFeed'

1 个答案:

答案 0 :(得分:0)

一种可能性是将这些方法放入一个单独的类中,在主类中用作mixin:

class VideoFeedMixin(object):
    def videoFeed(self):
        ...

然后:

from videoFunctions import VideoFeedMixin

class MainWindow(VideoFeedMixin, QtGui.QMainWindow, mainWindowUI.Ui_MainWindow):
    ...

现在self.timer.timeout.connect(self.videoFeed)将像以前一样工作。