使用PyQt和Qt设计器ui文件

时间:2014-03-26 14:14:48

标签: python pyqt pyqt4 qt-designer

我是PyQt的新手,我正在尝试直接从我的PyQt脚本中使用ui文件。我有两个ui文件,mainwindow.ui和landing.ui。单击主窗口上的“pushButton”按钮应打开着陆窗口。但是,单击该按钮不会像我预期的那样工作。这是代码(我只是试图解决问题所以代码非常粗糙):

from PyQt4 import QtCore, uic
from PyQt4 import QtGui
import os

CURR = os.path.abspath(os.path.dirname('__file__'))

form_class = uic.loadUiType(os.path.join(CURR, "mainwindow.ui"))[0]
landing_class = uic.loadUiType(os.path.join(CURR, "landing.ui"))[0]

def loadUiWidget(uifilename, parent=None):
    uifile = QtCore.QFile(uifilename)
    uifile.open(QtCore.QFile.ReadOnly)
    ui = uic.loadUi(uifilename)
    uifile.close()
    return ui

@QtCore.pyqtSlot()
def clicked_slot():
    """this is called when login button is clicked"""
    LandingPage = loadUiWidget(os.path.join(CURR, "landing.ui"))
    center(LandingPage)
    icon(LandingPage)
    LandingPage.show()


class MyWindow(QtGui.QMainWindow, form_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.pushButton.clicked.connect(clicked_slot)

class LandingPage(QtGui.QMainWindow, landing_class):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)

def center(self):
    """ Function to center the application
    """
    qRect = self.frameGeometry()
    centerPoint = QtGui.QDesktopWidget().availableGeometry().center()
    qRect.moveCenter(centerPoint)
    self.move(qRect.topLeft())

def icon(self):
    """ Function to set window icon
    """
    appIcon = QtGui.QIcon("icon.png")
    self.setWindowIcon(appIcon)


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    pixmap = QtGui.QPixmap(os.path.join(CURR, "splash.png"))
    splash = QtGui.QSplashScreen(pixmap)
    splash.show()
    app.processEvents()    
    MainWindow = MyWindow(None)
    center(MainWindow)
    icon(MainWindow)
    MainWindow.show()
    splash.finish(MainWindow)
    sys.exit(app.exec_())

我在做什么错误?

1 个答案:

答案 0 :(得分:10)

您的脚本存在两个主要问题:首先,您没有正确构建ui文件的路径;其次,您没有保留对着陆页窗口的引用(因此在显示后会立即收集垃圾)。

以下是如何构建加载ui文件的脚本部分:

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)