python - 如何在主窗口中更改 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)
为什么它不起作用?
解决方案
布局用于确定您正在使用的小部件的位置和大小,因此在您的情况下,即使您使用调整大小也不会改变大小,而是应该设置一个固定大小,这样布局就不会改变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_())
推荐阅读
- r - 如何在 R 中对描述性统计的列进行分组?
- java - Java 合并排序算法的问题
- python - VSCode:如何让 Run Above 只运行上面的单元格而不是上面的所有单元格?
- c# - 在消息队列级别拦截和修改键盘输入
- java - 如何在android的对话框片段中刷新片段?
- json - 将 ArrayType 中的值解包为 df 中的列
- c - 什么是 OpenGL 中的颜色缓冲区?
- scala - 如何将 TimeZone 添加到 Spark TimestampType 列?
- jira - 使用 Xray REST API 创建测试并链接到测试集
- android - EditText.getText() 可以为空吗?