- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我在 PySide2 Qt 5.13.0 中创建了一个 TableView
。我想要一个 TableView
来填充父项的宽度,但除非我拖动表格,否则它不会调整列的大小。从程序一开始,我就希望列更宽。
主要.py
import sys
from PySide2.QtCore import QUrl
from PySide2.QtQml import QQmlApplicationEngine, qmlRegisterType
from PySide2.QtWidgets import QApplication
from table_model import TableModel
import qml_rc # noqa: F401
if __name__ == "__main__":
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
qmlRegisterType(TableModel, "TableModel", 1, 0, "TableModel")
engine.load(QUrl("qrc:/main.qml"))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
主.qml
import QtQuick 2.13
import QtQuick.Controls 2.13
import TableModel 1.0
ApplicationWindow {
visible: true
Component.onCompleted: {
showMaximized()
}
TableView {
id: tableView
clip: true
anchors.fill: parent
model: TableModel {}
topMargin: columnsHeader.implicitHeight
columnWidthProvider: function () { return tableView.width / tableView.model.columnCount(); }
delegate: Rectangle {
implicitWidth: tableView.columnWidthProvider()
implicitHeight: 40
Text {
text: display
}
}
Row {
id: columnsHeader
y: tableView.contentY
z: 2
Repeater {
model: tableView.columns > 0 ? tableView.columns : 1
Rectangle {
width: tableView.columnWidthProvider()
height: 60
clip: true
Label {
id: headerText
width: parent.width
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
text: tableView.model.headerData(modelData, Qt.Horizontal)
elide: Text.ElideRight
clip: true
}
}
}
}
}
}
表格模型.py
from typing import Any, Optional
from PySide2.QtCore import QAbstractTableModel, QModelIndex, QObject, Qt
from table import Table
class TableModel(QAbstractTableModel):
def __init__(self, parent: QObject = None) -> None:
super().__init__(parent)
self._model_data = Table(
["This", "Is", "A", "Test", "Of", "Headers"],
[
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
["A", 1, 2, "B", "C", "D"],
["E", 3, 4, "F", "G", "H"],
["I", 5, 6, "J", "K", "L"],
["M", 7, 8, "N", "O", "P"],
])
def rowCount(self, parent=QModelIndex()) -> int:
return len(self._model_data.rows)
def columnCount(self, parent=QModelIndex()) -> int:
return len(self._model_data.headers)
def data(self, index: QModelIndex, role=Qt.DisplayRole) -> Optional[Any]:
if role != Qt.DisplayRole:
return None
if not self.checkIndex(index, QAbstractTableModel.CheckIndexOption.IndexIsValid):
return None
return self._model_data.rows[index.row()][index.column()]
def headerData(self, section: int, orientation, role) -> Optional[str]:
if role != Qt.DisplayRole:
return None
if section < 0 or section >= len(self._model_data.headers):
return None
return self._model_data.headers[section]
def reset_with_data(self, model_data: Table) -> None:
self.beginResetModel()
self._model_data = model_data
self.endResetModel()
表格.py
from dataclasses import dataclass
from typing import Any, List
@dataclass
class Table:
headers: List[str]
rows: List[List[Any]]
qml.qrc
<RCC>
<qresource prefix="/">
<file>main.qml</file>
</qresource>
</RCC>
运行:
pipenv run pyside2-rcc -o qml_rc.py qml.qrc
pipenv run python main.py
最佳答案
作为the docs指出:
Row heights and column widths
When a new column is flicked into view, TableView will determine its width by calling the columnWidthProvider function. TableView itself will never store row height or column width, as it's designed to support large models containing any number of rows and columns. Instead, it will ask the application whenever it needs to know.
TableView uses the largest implicitWidth among the items as the column width, unless the columnWidthProvider property is explicitly set. Once the column width is found, all other items in the same column are resized to this width, even if new items that are flicked in later have larger implicitWidth. Setting an explicit width on an item is ignored and overwritten.
Note: The calculated width of a column is discarded when it is flicked out of the viewport, and is recalculated if the column is flicked back in. The calculation is always based on the items that are visible when the column is flicked in. This means that it can end up different each time, depending on which row you're at when the column enters. You should therefore have the same implicitWidth for all items in a column, or set columnWidthProvider. The same logic applies for the row height calculation.
If you change the values that a rowHeightProvider or a columnWidthProvider return for rows and columns inside the viewport, you must call forceLayout. This informs TableView that it needs to use the provider functions again to recalculate and update the layout.
Since Qt 5.13, if you want to hide a specific column, you can return 0 from the columnWidthProvider for that column. Likewise, you can return 0 from the rowHeightProvider to hide a row. If you return a negative number, TableView will fall back to calculate the size based on the delegate items.
Note: The size of a row or column should be a whole number to avoid sub-pixel alignment of items.
The following example shows how to set a simple columnWidthProvider together with a timer that modifies the values the function returns. When the array is modified, forceLayout is called to let the changes take effect:
TableView {
id: tableView
property var columnWidths: [100, 50, 80, 150]
columnWidthProvider: function (column) { return columnWidths[column] }
Timer {
running: true
interval: 2000
onTriggered: {
tableView.columnWidths[2] = 150
tableView.forceLayout();
}
}
}
(强调我的)
所以在这种情况下,当 TableView 的宽度发生变化时,您应该调用 forceLayout()
.就我而言(Qt 5.13.1、PySide2 5.13.1、Linux)我还必须为 ApplicationWindow 设置宽度和高度:
import QtQuick 2.13
import QtQuick.Controls 2.13
import TableModel 1.0
ApplicationWindow {
visible: true
Component.onCompleted: {
showMaximized()
}
width: 640
height: 480
TableView {
id: tableView
clip: true
anchors.fill: parent
model: TableModel{}
topMargin: columnsHeader.implicitHeight
columnWidthProvider: function (column) {
return tableView.model ? tableView.width/tableView.model.columnCount() : 0
}
onWidthChanged: tableView.forceLayout()
delegate: Rectangle {
implicitWidth: tableView.columnWidthProvider(column)
implicitHeight: 40
Text {
text: display
}
}
Row {
id: columnsHeader
y: tableView.contentY
z: 2
Repeater {
model: tableView.columns > 0 ? tableView.columns : 1
Rectangle {
width: tableView.columnWidthProvider(modelData)
height: 60
clip: true
Label{
id: headerText
width: parent.width
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
text: tableView.model ? tableView.model.headerData(modelData, Qt.Horizontal): 0
elide: Text.ElideRight
clip: true
}
}
}
}
}
}
关于python - 具有动态宽度列的 QML TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57928843/
如果下一个元素的宽度超过指定布局的宽度,是否有 QML 布局或某些配置会自动将 QML 项目包装到下一行? 当我使用 QML GridLayout ,项目刚好离开窗口的边缘并被剪裁: GridLayo
如果下一个元素的宽度超过指定布局的宽度,是否有 QML 布局或某些配置会自动将 QML 项目包装到下一行? 当我使用 QML GridLayout ,项目刚好离开窗口的边缘并被剪裁: GridLayo
如何在 qml 文件之间发送变量或信号? http://i.stack.imgur.com/MChCG.png Mainwindow -> 创建组件Item2.qml MainWindow -> 创建
我正在做一些事情,我有一个名为“FloatingMenu”的类(它应该在 C++ 中管理菜单)及其在文件 FloatingMenu.qml 中用于 GUI 的 QML alter-ego。我有一个文件
我正在尝试做一些看似简单的事情,但失败了:定义一个简单的内联文本格式组件,然后用不同的文本多次实例化它。这是代码 Item { . . . Component { id: favButtonL
我可以在页面中使用 InvokeActionItem 轻松共享项目,但我需要能够在 ListView 项目中调用它。我设法触发了一个调用,但我不知道如何在触发它时添加数据。我不断收到错误消息 Invo
我如何在 QML 中检测 Window {} 之外的点击? Rectangle { id: topLevel height: 400; width: 400 Window {
我试过 : var child = grid.children[slot1]; grid.children[slot1] = grid.children[slot2]; grid.children[s
例如,我希望创建一个包含 100 个文本编辑器的 qml 窗口,如何在循环中创建它?那可能吗? 最佳答案 循环是命令式代码,所以它不是 QML,而是 Javascript 或 C++。所以当然,你可以
这是我的 QML 文件,其中包含一个文本组件: import QtQuick 2.0 Item { id: idItmWrapText Text { id: idTxt
我正在寻找一种方法来显示一个文本提示,说明预期的输入作为对用户的建议。以谷歌搜索栏为例: 是否有我缺少的属性,或者这是必须通过脚本来实现的? 最佳答案 Qt Quick 输入项上不存在该属性。您可以为
为 qml 项设置背景的最简单方法是让子矩形的 anchor 完全填满父项: Item { width: 320 height: 240 Rectangle {
我想将属性动态添加到 QML 元素: Item { id: dynamicProperty; property int first; Component.onCompleted: { /*
我用 PySide 和 QML 编写了某种安装程序。按照设计,它必须是多页的。而且我想将要从 QML 表单调用的插槽划分为不同的对象(理想情况下,划分为模块,但据我了解,带有插槽的对象必须继承 QOb
QML 中有没有办法用 opacity: 0 创建一个矩形?仍然有可见的边界?如果没有,有关如何解决它的任何建议? 谢谢 最佳答案 不,不透明度适用于项目的完整视觉方面(并且不透明度:0 使项目完全不
属性变体 a:{}似乎不起作用。 a 最终未定义,而不是一个空字典。 我对 Javascript 不是很有经验...初始化属性以保存空字典的正确方法是什么? 以下 qml 在控制台上打印“qrc:/m
我在 SO 上查看了大量关于 QML 内容边距的问题,但所有答案都指向缺少 spacing: 0 属性。我已经完成了所有这些,但仍然有一些我无法消除的奇怪空间。任何人都可以解释为什么这个 QML 代码
我有一个用于样式定义的 QML 单例,定义如下: pragma Singleton import QtQuick 2.2 import QtQuick.Controls 1.1 import QtQu
这是以下代码的结果: 主.qml import QtQuick 2.8 Item { Reusable { index: 1234 // reusable with
属性变体 a:{}似乎不起作用。 a 最终未定义,而不是一个空字典。 我对 Javascript 不是很有经验...初始化属性以保存空字典的正确方法是什么? 以下 qml 在控制台上打印“qrc:/m
我是一名优秀的程序员,十分优秀!