[英]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()
這將打開一個窗口來管理目錄(文件)。 但是在我的MainApp用戶界面之外(因此,打開了一個新窗口),我想在其中嵌入此外部窗口,如下所示:
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()
我如何將此窗口嵌入到MainApp UI中,使其成為我的主要圖形應用程序(如Widget)的一部分?
謝謝!
一種可能的解決方案是使用布局將小部件放置在窗口內。 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_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.