ohad987
ohad987

Reputation: 336

How to import UI from Qt Designer

I'm making a simple GUI that only includes a button. I decided to do it with PyQt Designer.

I decided that the UI generated by the Designer will be in one file, and the rest will be in another module that will import the UI.

The generated file by PyQt Designer is:

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_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(326, 232)
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(104, 30, 101, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Form)

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

The main file that imports it looks like this:

import sys
from PyQt4 import QtCore, QtGui
from stacko import Ui_Form

class test(Ui_Form):
    self.pushButton.connect.clicked(self.onClick)
    def onClick(self):
        print "clicked!"

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

I want that when the button is clicked it will print out 'clicked!'. For some reason, it's not working for me. I read a lot on classes/sub-classes and OOP but I still couldnt get it working.

It raises an error: NameError: name 'self' is not defined

Upvotes: 1

Views: 4274

Answers (1)

ekhumoro
ekhumoro

Reputation: 120608

Here is what your main module should look like:

import sys
from PyQt4 import QtCore, QtGui
from stacko import Ui_Form

class Test(QtGui.QWidget, Ui_Form):
    def __init__(self):
        super(Test, self).__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.onClick)

    def onClick(self):
        print "clicked!"

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    window = Test()
    window.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions