Recently, I used QML's TableView in a project because I needed to dynamically adjust the size of each cell. So I needed to refresh it.
Let's look at the official example directly:
import QtQuick 2.12
import TableModel 0.1
TableView {
anchors.fill: parent
columnSpacing: 1
rowSpacing: 1
clip: true
model: TableModel {}
delegate: Rectangle {
implicitWidth: 100
implicitHeight: 50
Text {
text: display
}
}
}
If you need to dynamically adjust the size, you need to add the following code under TableView:
rowHeightProvider: function (row) {
return xxxWidth;
}
And use forceLayout()
for specific documentation, you can click here
Calling this function re-evaluates the size and position of each visible row and column. This is needed if the functions assigned to rowHeightProvider or columnWidthProvider return different values than what is already assigned.
Here it is explained that the height and width will be recalculated, but the detail is each visible row and column., which means that invisible cells will not be recalculated.
The result is that originX and originY will become unpredictable.
If any other control uses TableView's contentX, contentY, then the calculation will not be correct because contentX is calculated based on originX.
How to truly refresh the entire table.
-
TableView.forceLayout(): Only refreshes the visible interface.
-
Resetting visible: Does not refresh.
-
layoutChanged() in the model will also only refresh the visible interface.
After trying various methods, the solution is to reset the model, the code is as follows, resetting will move contentX back to its original position. According to the documentation, TableView only has 1fps, so there is usually no visual impact.
Responding to changes in the model are batched so that they are handled only once per frame.
var firstIndex = table_view.contentX / (tableCellWidth);
table_view.model = null;
table_view.model = table_model;
table_view.contentX = (tableCellWidth) * firstIndex;