Working with PyQt and Qt designer ui files

前端 未结 1 771
再見小時候
再見小時候 2021-01-15 03:16

I\'m new to PyQt and I\'m trying to work with ui files directly from within my PyQt script. I have two ui files, mainwindow.ui and landing.ui. Clicking on a button \'pushBut

相关标签:
1条回答
  • 2021-01-15 04:03

    There are two main problems with your script: firstly, you are not constructing the path to the ui files correctly; and secondly, you are not keeping a reference to the landing-page window (and so it will get garbage-collected immediately after it is shown).

    Here is how the part of the script that loads the ui files should be structured:

    import os
    from PyQt4 import QtCore, QtGui, uic
    
    # get the directory of this script
    path = os.path.dirname(os.path.abspath(__file__))
    
    MainWindowUI, MainWindowBase = uic.loadUiType(
        os.path.join(path, 'mainwindow.ui'))
    
    LandingPageUI, LandingPageBase = uic.loadUiType(
        os.path.join(path, 'landing.ui'))
    
    class MainWindow(MainWindowBase, MainWindowUI):
        def __init__(self, parent=None):
            MainWindowBase.__init__(self, parent)
            self.setupUi(self)
            self.pushButton.clicked.connect(self.handleButton)
    
        def handleButton(self):
            # keep a reference to the landing page
            self.landing = LandingPage()
            self.landing.show()
    
    class LandingPage(LandingPageBase, LandingPageUI):
        def __init__(self, parent=None):
            LandingPageBase.__init__(self, parent)
            self.setupUi(self)
    
    0 讨论(0)
提交回复
热议问题