如何在主 window 中更改 PyQt5 目录视图的大小?

How to change the size of PyQt5 directory view in the main window?

我正在做一个 PyQt5 项目,它需要 PyQt5 的文件夹查看器 QTreeView。为了放更多的东西,我尝试改变树视图的大小但没有成功。这是来自 Pythonspot 的代码:

import sys
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout
from PyQt5.QtGui import QIcon

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 file system view - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        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("Dir View")
        self.tree.resize(640, 200)

        windowLayout = QVBoxLayout()
        windowLayout.addWidget(self.tree)
        self.setLayout(windowLayout)

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

我通过

更改树视图
self.tree.resize(640, 200)

为什么它不起作用?

布局用于确定您正在使用的小部件的位置和大小,因此在您的情况下,即使您使用调整大小,大小也不会改变,相反,您应该设置一个固定大小,这样布局就不会更改 QTreeView.

的大小
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class App(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 file system view - pythonspot.com'
        self.left, self.top, self.width, self.height = 10, 10, 640, 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

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

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

        self.tree.setWindowTitle("Dir View")
        self.tree.setFixedSize(640, 200)

        windowLayout = QtWidgets.QVBoxLayout(self)
        windowLayout.addWidget(self.tree, alignment=QtCore.Qt.AlignTop)

        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())