如何在 PyQt5 的 Main Window 中嵌入 window

How to embed a window in a Main Window in PyQt5

我有如下所示的代码片段:

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()

这会打开一个window来管理目录(文件)。但是在我的 MainApp UI 之外(因此,打开一个新的 window),我想在其中嵌入这个外部 window,如下所示:

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

    def initUI(self):
        """This method creates our GUI"""

        # Box Layout to organize our GUI
        # labels
        types1 = QLabel('Label', self)
        types1.resize(170, 20)
        types1.move(1470, 580)

        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()

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

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

我如何将这个 window 嵌入到我的 MainApp UI 中,作为我的主要图形应用程序的一部分,就像一个小部件?

谢谢!

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

您必须做的是创建一个中央小部件并为其建立布局:

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