Twimnox
Twimnox

Reputation: 365

Access widgets added in Qt Designer

I am creating a Qt GUI with Qt Designer. In the designer, I place two widgets in a QSplitter (one widget on the left, other widget on the right).

The thing is that now I want to control each widget separately, but my MainWindow has the GUI python code of everything in it, including both widgets and their contents (labels, text labels, etc).

Is there a way to access the widgets separately? Here's my code:

On the MainWindow:

if __name__ == "__main__":

    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = mw_gui.Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    img_widget = ImageWidget(MainWindow)

    sys.exit(app.exec_())

In the class that I want to use to control the right side widget:

class ImageWidget(QtGui.QWidget):
    def __init__(self, parent, variables):
        # self.ui = ui
        # self.variables = variables
        if not isinstance(parent, QtGui.QMainWindow):
            raise TypeError('parent must be a QMainWindow')
        super(ImageWidget, self).__init__()

        self._parentWidget = parent

I want to access self.imglabel, which is inside the right widget, but it doesn't seem to find it.

Upvotes: 2

Views: 2422

Answers (2)

ekhumoro
ekhumoro

Reputation: 120768

You should create a subclass for the main-window, inheriting from both QMainWindow and Ui_MainWindow. With this approach, all the widgets added in Qt Designer will become accessible as instance attributes:

from PySide import QtGui
from mw_gui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.imglabel.setPixmap(QtGui.QPixmap('image.png'))

if __name__ == "__main__":

    import sys
    app = QtGui.QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())

Doing things this way also means separate controller classes are probably not necessary, since you can just add methods to the MainWindow class. The design is much simpler if everything is in one namespace.

Upvotes: 2

Gwen
Gwen

Reputation: 1450

You should be able to find a widget with its name and type:

imglabel = self.ui.findChild(QtGui.QLabel, "imglabel")

Upvotes: 1

Related Questions