【发布时间】:2021-07-08 12:25:16
【问题描述】:
我有一个使用 PyQt5 的应用程序,它在 QML 中有一个表格视图,可以从 pandas 数据帧中获取数据。
每次我使用新的数据框加载更新数据时,我都需要列宽以自动适应内容的宽度。我在论坛上没有找到关于这个主题的任何新内容,而且旧答案非常令人困惑,我不敢相信在 2021 年对于餐桌治疗中如此常见的事情没有简单的解决方案。
我的QML代码如下:
TableView {
id: tableView
antialiasing: true
width: parent.width
height: parent.height
columnWidthProvider: function (column) { return 200; }
rowHeightProvider: function (column) { return 60; }
leftMargin: rowsHeader.implicitWidth
topMargin: columnsHeader.implicitHeight
rightMargin: columnsHeader.implicitHeight
Layout.fillHeight: true
model: table_model
delegate: Rectangle {
color: "transparent"
Text {
text: display
anchors.fill: parent
anchors.margins: 10
horizontalAlignment: Text.AlignHCenter
color: {
if (temaescolhido.currentText == 'Claro') return 'Black'
return 'White'
}
font.pixelSize: 15
verticalAlignment: Text.AlignVCenter
}
}
Rectangle { // mask the headers
z: 3
color: "transparent"
y: tableView.contentY
x: tableView.contentX
width: tableView.leftMargin
height: tableView.topMargin
}
Row {
id: columnsHeader
y: tableView.contentY
z: 2
Repeater {
model: tableView.columns > 0 ? tableView.columns : 1
Label {
width: tableView.columnWidthProvider(modelData)
height: 35
text: table_model.headData(modelData, Qt.Horizontal)
color: 'green'
font.bold: true
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
background: Rectangle { color: "#adadad" }
}
}
}
Column {
id: rowsHeader
x: tableView.contentX
z: 2
Repeater {
model: tableView.rows > 0 ? tableView.rows : 1
Label {
width: 35
height: tableView.rowHeightProvider(modelData)
text: table_model.headData(modelData, Qt.Vertical)
color: 'green'
font.bold: true
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
background: Rectangle { color: "#adadad" }
}
}
}
ScrollIndicator.horizontal: ScrollIndicator { }
ScrollIndicator.vertical: ScrollIndicator { }
}
【问题讨论】:
-
旧答案可能令人困惑,因为 TableView 仅在 2.12 中正式添加,在此之前我们使用 ListView 制作大多数表格。如果我有时间,我将尝试回答。这个功能在 5.12 到 5.15 版本之间发生了变化,所以为了提供一些有用的东西,你的目标是哪个版本的 Qt(或 PyQt5)?
-
您好,感谢您的回复。我将 qt 5.15.4 与 Qtquick 一起使用。但是我正在考虑使用 qtwidgets 来完成 python 中的所有代码(没有 qml),因为我对这种语言有更多的了解。你认为我从 qtquick 切换到 qtwidgets 会失去太多的创作可能性吗?
-
我认为 Widgets vs Quick 没有简单的答案。 Quick 有使用 OpenGL 来利用 3D GPU 的动画,但我读过 Widgets 与 matplotlib 有更好的集成,所以这取决于你想要做什么