Zeke Xiao

Zeke Xiao


The problem of changing columnWidth and rowHeight in TableView in QtQuick/QML.

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 directly look at the official example:

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 under TableView:

rowHeightProvider: function (row) {
    return xxxWidth;

And use forceLayout(). For more details, 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 it will recalculate the height and width, but the detail is that it only applies to 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 it will not be calculated correctly because contentX is calculated based on originX.

How to truly refresh everything, refresh the entire table.

  1. TableView.forceLayout(): Only refreshes the visible interface.

  2. Resetting visible: Does not refresh.

  3. layoutChanged() in the model only refreshes the visible interface.

After trying various methods, the solution is to reset the model. The code is as follows: Reset the contentX and then move it 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;
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.