如何在PyQt5的主窗口中嵌入窗口

2024-09-25 14:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下代码片段:

self.model = QFileSystemModel()
self.model.setRootPath('')
self.tree = QTreeView()
self.tree.setModel(self.model)

self.tree.setAnimated(False)
self.tree.setIndentation(20)
self.tree.setSortingEnabled(True)

self.tree.setWindowTitle("Directory Viewer")
self.tree.resize(323, 300)
self.tree.show()

这将打开一个管理目录(文件)的窗口。但在我的MainApp UI(打开一个新窗口)中,我想嵌入这个外部窗口,如下所示:

^{pr2}$

如何将这个窗口嵌入到我的mainappui中,作为主图形应用程序的一部分,比如小部件?在

谢谢!在


Tags: 代码selffalsetruetreemodeldirectorysetmodel
1条回答
网友
1楼 · 发布于 2024-09-25 14:31:47

一个可能的解决方案是使用布局来定位窗口内的小部件。QMainWindow的情况很特殊,因为您不必建立一个布局,它有一个预定义的布局:

enter image description here

您需要做的是创建一个中心小部件并建立布局:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys


class MainApp(QMainWindow):
    """This is the class of the MainApp GUI system"""
    def __init__(self):
        """Constructor method that inherits methods from QWidgets"""
        super().__init__()
        self.initUI()

    def initUI(self):
        """This method creates our GUI"""
        centralwidget = QWidget()
        self.setCentralWidget(centralwidget)
        lay = QVBoxLayout(centralwidget)
        # Box Layout to organize our GUI
        # labels
        types1 = QLabel('Label')
        lay.addWidget(types1)

        self.model = QFileSystemModel()
        self.model.setRootPath('')
        self.tree = QTreeView()
        self.tree.setModel(self.model)

        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setSortingEnabled(True)
        lay.addWidget(self.tree)

        self.setGeometry(50, 50, 1800, 950)
        self.setFixedSize(self.size())
        self.setWindowTitle('MainApp')
        self.setWindowIcon(QIcon('image/logo.png'))
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainApp()
    sys.exit(app.exec_())

enter image description here

相关问题 更多 >