Compozitor
Compozitor

Reputation: 59

How to select a row in TableView (QML)?

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?

Upvotes: 3

Views: 6027

Answers (2)

Javier Palacios
Javier Palacios

Reputation: 400

You can also use ItemDelegate for the delegates, using scoped model.display to access the model data (itemDelegate has an inherited display property). You must also explicitly handle the currently selected row, and with those to item, in a simple case this should work

    property int selectedRow: 1

    delegate: ItemDelegate {
        highlighted: row == view.selectedRow
        onClicked: view.selectedRow = row
        text: model.display
    }

Upvotes: 2

Neilana
Neilana

Reputation: 104

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.

Upvotes: 4

Related Questions