Reputation: 595
I've created a interface in Qt as .ui file and then converted it to a python file. Then, I wanted to add some functionality to the components such as radio button, etc. For doing so, I tried to re-implement the class from Qt and add my events. But it gives the following error:
self.radioButton_2.toggled.connect(self.radioButton2Clicked)
NameError: name 'self' is not defined
My first question is whether this is the correct/proper way to deal with classes generated by Qt? And second, why do I get the error?
My code is here:
import sys
from PySide import QtCore, QtGui
from InterfaceClass_Test01 import Ui_MainWindow
class MainInterface(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainInterface, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def setupUi(self, MainWindow):
super(MainInterface, self).setupUi(parent, MainWindow)
self.radioButton.toggled.connect(self.radioButtonClicked)
self.radioButton_2.toggled.connect(self.radioButton2Clicked)
self.radioButton_3.toggled.connect(self.radioButton3Clicked)
def radioButton3Clicked(self, enabled):
pass
def radioButton2Clicked(self, enabled):
pass
def radioButtonClicked(self, enabled):
pass
Upvotes: 1
Views: 1422
Reputation: 120578
The generated files are a little unintuitive. The UI class is just a simple wrapper, and is not a sub-class of your top-level widget from Qt Designer (as you might expect).
Instead, the UI class has a setupUi
method that takes an instance of your top-level class. This method will add all the widgets from Qt Designer and make them attributes of the passed in instance (which would normally be self
). The attribute names are taken from the objectName
property in Qt Designer. It is a good idea to reset the default names given by Qt to more readable ones so that they are easy to refer to later. (And don't forget to re-generate the UI module after you've made your changes!)
The module that imports the UI should end up looking like this:
import sys
from PySide import QtCore, QtGui
from InterfaceClass_Test01 import Ui_MainWindow
class MainInterface(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainInterface, self).__init__(parent)
# inherited from Ui_MainWindow
self.setupUi(self)
self.radioButton.toggled.connect(self.radioButtonClicked)
self.radioButton_2.toggled.connect(self.radioButton2Clicked)
self.radioButton_3.toggled.connect(self.radioButton3Clicked)
def radioButton3Clicked(self, enabled):
pass
def radioButton2Clicked(self, enabled):
pass
def radioButtonClicked(self, enabled):
pass
Upvotes: 1