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

时间:2018-11-08 20:03:39

标签: python python-3.x pyqt5 qtreeview

我正在研究一个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)

为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

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