gpt4 book ai didi

python - 使用 PyQt 和 Qt 设计器 ui 文件

转载 作者:行者123 更新时间:2023-11-28 19:49:12 33 4
gpt4 key购买 nike

我是 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_())

我犯了什么错误??

最佳答案

您的脚本有两个主要问题:首先,您没有正确构建 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)

关于python - 使用 PyQt 和 Qt 设计器 ui 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22663716/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com