【问题标题】:Updating child widget in Qt在 Qt 中更新子小部件
【发布时间】:2015-11-10 18:22:35
【问题描述】:

我有一个包含以下类的简单项目

  1. 类 MainWindow(QMainWindow)
  2. 类主页(QWidget)
  3. 类登录(QWidget)

我想要的只是能够嵌套 QWidget 类(使它们成为 QMainWindow 的子类)并将它们显示在 MainWindow 内。在 MainWindow 中调用 QWidgets 后,我无法弄清楚如何让它们“出现”。

代码如下:

import sys
from gui.MainWindow import Ui_MainWindow
from gui.home import Ui_Home
from gui.login import Ui_Login
from PyQt4.QtGui import QMainWindow, QApplication, QWidget

class Home(QWidget, Ui_Home):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)

class Login(QWidget, Ui_Login):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)

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

        #INSERT pushButton.click to go to HOME here
        #INSERT pushButton.click to go to LOGIN here

    def setHome(self):    
        self.label_Screen.setText("HOME")
        self.mainwidget = Home()
        #NEEDS SOMETHING HERE

    def setLogin(self):    
        self.label_Screen.setText("LOGIN")
        self.mainwidget = Login()
        #NEEDS SOMETHING HERE

if __name__ == '__main__':
    app = QApplication(sys.argv)
    Main = MainWindow()
    Main.show()
    sys.exit(app.exec_())

我想我只是需要一些我标记为“#NEEDS SOMETHING HERE”的东西,但我不确定是什么!

干杯!

已解决:感谢kh25

只需向 QMainWindow 添加一个布局并将 setHome 更改为:

def setHome(self):    
    self.label_Screen.setText("HOME")
    self.currentScreen = Home()
    self.layout.addWidget(self.currentScreen)
    self.setLayout(self.layout)

setLogin 方法也应该这样做。

【问题讨论】:

  • 我认为您需要通过一些 Qt 示例来了解如何处理布局和子小部件。 Qt 自带了很多。

标签: python qt user-interface pyqt


【解决方案1】:

您需要先创建一个布局并将小部件添加到此布局。有各种类型的布局。在这里阅读:

http://doc.qt.io/qt-4.8/layout.html

对于像你这样的简单案例,我建议使用 QHBoxLayout 或 QVBoxLayout。

声明此布局。在每个 Login 和 Home 小部件的布局上调用 addWidget(),然后在 QMainWindow 上调用 setLayout()。

【讨论】:

  • 工作就像一个魅力!谢谢!