Search code examples
pythonpyqtpyqt4qt-designer

PyQt change element in .ui file


I have the pyqt-based app and design in .ui file. They communicate with each other using signals and slots, but I have a need to change the properties of the elements in the design. Is it possible to do this? Pseudo-code what I need:

@pyqtSlot()
def click_my_btn(self, sender):
    button = QtGui.QPushButton(button)
    button.hide()

Solution

  • You can access elements from .ui designs by their names. E.g. there is a design for main window with one button:

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>MainWindow</class>
     <widget class="QMainWindow" name="MainWindow">
      ...
      <widget class="QPushButton" name="btn"/>
      ...
     </widget>
    </ui>
    

    You init widget object with it:

    class MainWindow(QMainWindow):
        def __init__(self):
            QMainWindow.__init__(self)
            uic.loadUi('window.ui', self)
    
    main_window = MainWindow()
    

    Then from your method you can get access to that button:

    @pyqtSlot()
    def click_my_btn(self, sender):
        main_window.btn.hide()