Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a row in TableView (QML)?

Tags:

qt

qml

qt6

In Qt 6, all QtQuick 1 components are removed. I want to rewrite an old application using Qt 6. The application uses the TableView control version 1.

How can I select a row in a new control TableView and get the values of all cells in the row?

like image 269
Compozitor Avatar asked Nov 16 '25 22:11

Compozitor


1 Answers

I've had the same problem. Here's what worked for me.

I use Qt 5.12 and TableView from QtQuick 2.12.

I had troubles with getting an index of clicked row. I've found that the DelegateChooser and DelegateChoice components allows you to access the row and column properties in TableView. After you got row and column form DelegateChoice you can use it to access data in model with QAbstractItemModel methods index(...) and data(...) like:

var idx = model.index(row, column)
var data = model.data(idx)

Here's full example:

    import QtQuick 2.12             // TableView
    import Qt.labs.qmlmodels 1.0    // DelegateChooser
    
    // ...
    
    TableView {  
      id: usersTable
      model: tableModel
      
      anchors.fill: parent
      
      delegate: DelegateChooser
      {
        DelegateChoice
        {
          delegate: Rectangle {
            implicitWidth: 100
            implicitHeight: 50
            Text { text: display }
            
            MouseArea {
              anchors.fill: parent
              onClicked:
              {            
                // print value from clicked cell
                var idx = tableModel.index(row,column)
                console.log("Clicked cell: ", tableModel.data(idx))
                
                // print values from all cells in a row
                console.log("Clicked row: ")
                for (var i = 0; i < tableModel.columnCount(); i++)
                {
                  var idx2 = tableModel.index(row,i)
                  var data = tableModel.data(idx2)
                  console.log(data)
                }
              } // onClicked
            } // MouseArea
          } // Rectangle
        }// DelegateChoice
      } // DelegateChooser
    } // TableView

DelegateChooser allows you to create multiple delegates for the model. I'm not sure whether it's good practice or not to use chooser in case you have only one delegate (like in example above). But that workaround works perfectly fine.

like image 199
Neilana Avatar answered Nov 18 '25 19:11

Neilana