UI Application not loading PyQt5

2019-06-11 17:18发布

问题:

I don't know why this application doesn't load my ui. I've written the exact codes that I've found on the internet but didn't get any result.

from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys


class Receipt(QMainWindow):

    def __init__(self):
        super().__init__()
        self.ui = None
        self.load_ui()
        self.load_signals()

    def load_ui(self):
        self.ui = loadUi('window.ui')
        self.show()

    def load_signals(self):
        pass

app = QApplication(sys.argv)
receipt = Receipt()
sys.exit(app.exec_()) 

回答1:

According to the documentation:

PyQt5.uic.loadUi(uifile[, baseinstance=None[, package=”[, resource_suffix=’_rc’]]])

Load a Qt Designer .ui file and returns an instance of the user interface.

Parameters:

uifile – the file name or file-like object containing the .ui file.

baseinstance – the optional instance of the Qt base class. If specified then the user interface is created in it. Otherwise a new instance of the base class is automatically created.

package – the optional package that is the base package for any relative imports of custom widgets.

You must pass as a parameter the self instance, as I show below

self.ui = loadUi('window.ui', self)


回答2:

Try passing in QMainWindow as an argument to your Receipt class like this:

app = QApplication(sys.argv)
receipt = Receipt(QMainWindow)
sys.exit(app.exec_()) 

This should set the main window to your class and display the app when you execute it.