PyQt - 如何将signat连接到自定义插槽/功能

时间:2013-05-22 17:12:18

标签: pyqt qt-designer qt-signals

我是PyQt编程的新手。我正在尝试创建简单的应用程序,但在将信号连接到自定义功能时触发。每次我跑 我得到相同的错误“AttributeError:'AppGui'对象没有属性'chk_fun'” 这是一个简单的按钮示例。我想要的是在点击按钮时在终端上打印一些文本。我使用Qt Designer创建对话框并使用pyuic4转换为.py。这是从pyuic4“ui_test.py”生成的代码

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'test.ui'
#
# Created: Wed May 22 20:18:43 2013
#      by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 300)
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(110, 70, 161, 91))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "PushButton", None))

这是实际的main.py内容。

#!/usr/bin/env python

import sys

from PyQt4 import QtCore, QtGui
from ui_test import Ui_Dialog

class AppGui(QtGui.QDialog,Ui_Dialog):

    def __init__(self):
        QtGui.QDialog.__init__(self)

        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

    self.ui.pushButton.clicked.connect(self.chk_fun)

    def chk_fun(self):
        print("Good.") 

app = QtGui.QApplication(sys.argv)
window = AppGui()
ui = Ui_Dialog()
window.show()
sys.exit(app.exec_())

我哪里出错?

1 个答案:

答案 0 :(得分:3)

缩进是错误的。调用connect的行应缩进为__init__方法正文。

class AppGui(QtGui.QDialog,Ui_Dialog):

    def __init__(self):
        QtGui.QDialog.__init__(self)

        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.chk_fun)