带水平标题的QML表格视图-列宽



我正在开发一个跨平台应用程序。Rigth现在,我正在开发Window 10,Qt 5.15.2 MinGw 32位。在我的应用程序中,我在qml端有一个TableView,在c++侧有一个从QSqlQueryModel派生的模型。我使用的是QtQuick 2.15。

TableView包含来自数据库的数据,但我需要一个Header来显示列名,所以我在TableView中添加了一个Row组件。函数columnWidthProvider出现问题。我从文档中知道,如果我什么都不指定,那么列的宽度会被调整,以使列中的项目适合它。但我需要知道这个宽度值,这样我就可以将它赋予行标题组件中的项目,这样列就可以按照它们的corrispive"对齐;名称";。

这是我的以下代码:

TableView {
id: tableViewid
anchors {
top: parent.top
left: parent.left
right: parent.right
bottom: goToLapsButtonId.top
topMargin: 10
leftMargin: 10
rightMargin: 10
bottomMargin: 10
}
columnWidthProvider: function (column) {
if (column === 0)
return 0;
}
rowHeightProvider: function (column) {}
topMargin: columnsHeader.implicitHeight
model: masterController.ui_databaseController.ui_tableModel
clip: true
property int selectedRow : -1
delegate: Rectangle {
id: modelrect
implicitWidth: textId.implicitWidth + 50
implicitHeight: textId.implicitHeight + 10
Text {
id: textId
text: display
anchors.fill: parent
color: row == tableViewid.selectedRow ? 'white' : 'black'
font.bold: row == tableViewid.selectedRow
font.pixelSize: 14
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
}
color: row == tableViewid.selectedRow ? "#AA0000ff" : "#AAffffff"
MouseArea {
anchors.fill: parent
onClicked: {
if (tableViewid.selectedRow == row)
tableViewid.selectedRow = -1
else
tableViewid.selectedRow = row
}
}
}
Row {
id: columnsHeader
y: tableViewid.contentY
z: 2
Repeater {
id: headerItems
model: tableViewid.columns > 0 ? tableViewid.columns : 1
Label {
width: tableViewid.columnWidthProvider(modelData)
height: 20
text: masterController.ui_databaseController.ui_tableModel.headerData(modelData, Qt.Horizontal)
color: '#ffffff'
font.pixelSize: 15
padding: 10
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
background: Rectangle {
color: "#000022"
}
}
}
}
onModelChanged: forceLayout()
}

关于我该怎么做有什么建议吗?我设法做了相反的事情,为columnWidthProvider:使用了这个函数

columnWidthProvider: function (column) {
if (column === 0)
return 0;
return headerItems.itemAt(column).implicitWidth + 10
}

在这种情况下,列名与列值对齐,但如果列中的项目大于列名,则会被截断。

提前感谢您的帮助。

我解决了引入这个组件的问题,我不知道QML HorizontalHeaderView,它只能从Qt 5.15中获得。有了这个组件,我不再需要调整标题的列大小,因为它是由组件自动完成的。

最新更新