Home > OS >  QtCreator's UI is not applied to the window, it's always empty (Qt for Python)
QtCreator's UI is not applied to the window, it's always empty (Qt for Python)

Time:01-24

I have a fresh QtCreator installation, and I set it up to run using a fresh install of Python3.8 on which I pip-installed both pyside2 and pyside6.

When I create a new Qt for Python - Window (UI file) application, whatever I do to the UI file the window always shows up empty and with the default size when I run the app.

I've tried with a QDialog, QMainApplication, using Pyside2 or Pyside6, I've checked that it was correctly loading the UI (and the right one) - no dice. It just won't update, and appears not to have any reason not to.

Default code for completeness:

# This Python file uses the following encoding: utf-8
import os
from pathlib import Path
import sys

from PySide2.QtWidgets import QApplication, QDialog
from PySide2.QtCore import QFile
from PySide2.QtUiTools import QUiLoader


class Dialog(QDialog):
    def __init__(self):
        super(Dialog, self).__init__()
        self.load_ui()

    def load_ui(self):
        loader = QUiLoader()
        path = os.fspath(Path(__file__).resolve().parent / "form.ui")
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        loader.load(ui_file, self)
        ui_file.close()

if __name__ == "__main__":
    app = QApplication([])
    widget = Dialog()
    widget.show()
    sys.exit(app.exec_())

(In the UI I just drag-dropped a button right in the middle and saved the file)

Am I forgetting something fundamental? I'm only used to programming in C using QtCreator.

CodePudding user response:

I was expecting this to work right out of the box, but it's not.

This only dynamically load the UI as a new widget, with this custom class as a parent.

If I want signals and slots to work, the only thing I've found was to add a custom build step:

Command: <path to pyside6 install, use pip show to know where>\uic.exe

Arguments: <filename of the .ui file> -o <the python translation .py which will serve as baseclass> -g python

Working directory: [your project dir]

Then signals and slots need to be connected manually, so QtCreator really only enables you to draw the user interface but all the logic still needs to be done by hand. Component variables are normally named after their UI name, but you can see for yourself in the baseclass file. This is a big step back from how QtCreator is used in C ("go to slot" will not work).

Code to use:

import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import QFile
from PySide6.QtUiTools import QUiLoader

from YourGenPyFileName import Ui_YourUIName

class MainWindow(QMainWindow, Ui_YourUIName):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)

if __name__ == "__main__":
    app = QApplication([])
    widget = MainWindow()
    widget.show()
    sys.exit(app.exec_())
  • Related