Pergunta

I am new to PyQt programming. I am trying to create simple application but struck while connecting signal to custom function. Every time i run i get the same error "AttributeError: 'AppGui' object has no attribute 'chk_fun'" Here is the simple pushbutton example.All i wanted is to get some text printed in terminal when pushbutton is clicked. I used Qt Designer to create dialog and converted in to .py using pyuic4. Here is the code generated from 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))

and here is the actual main.py content.

#!/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_())

Where am i getting wrong?

Foi útil?

Solução

The indentation is wrong. The line with call of connect should be indented as __init__ method body.

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top