首页 > 解决方案 > 如何在主窗口中更改 PyQt5 目录视图的大小?

问题描述

我正在开发一个 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)

为什么它不起作用?

标签: pythonpython-3.xpyqt5qtreeview

解决方案


布局用于确定您正在使用的小部件的位置和大小,因此在您的情况下,即使您使用调整大小也不会改变大小,而是应该设置一个固定大小,这样布局就不会改变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_())

推荐阅读