belox86
belox86

Reputation: 11

How can i enable selection on TableView in QML Qt6.3?

I'm having trouble in make selection on QML model/view in Qt6.3.

In order to understand the behaviour i took the example given by Qt on the documentation of Table View about selection (see here). This is my whole main.qml file:

import QtQuick 
import QtQuick.Controls
import Qt.labs.qmlmodels


Window {
id: mainWin
visible: true
width: 640
height: 480
title: qsTr("QML Test")

TableView {
    id: tableView
    anchors.fill: parent
    clip: true

    model: TableModel {
        TableModelColumn { display: "name" }
        rows: [ { "name": "Harry" }, { "name": "Hedwig" } ]
    }

    selectionModel: ItemSelectionModel {
        model: tableView.model
    }

    delegate: Rectangle {
        implicitWidth: 100
        implicitHeight: 30
        color: selected ? "blue" : "lightgray"

        required property bool selected

        Text { text: display }
    }
}

}

and a very basic main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
#if defined(Q_OS_WIN)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

The application start, and the table is shown with proper data, but rows are not selectable.

What am i missing?

Thank you.

Michele

Upvotes: 0

Views: 603

Answers (1)

iam_peter
iam_peter

Reputation: 3924

You need to do the selection yourself. The example only shows how to render the selected state, but not how to actually select something. In order to select an item in the ItemSelectionModel you could add the following to your Rectangle delegate.

MouseArea {
    anchors.fill: parent
    onClicked: tableView.selectionModel.select(tableView.model.index(index, 0),
                                                ItemSelectionModel.Select)
}

When the Rectangle is clicked it will add the item via its index to the selection model. Have a look at the different selection flags. https://doc.qt.io/qt-6/qml-qtqml-models-itemselectionmodel.html#select-method

Upvotes: 1

Related Questions