简体   繁体   中英

TableView replacement for TableViewColumn in Qt Quick 2

In Qt Quick Controls 1 we can style different columns from a model with TableViewColumn :

TableView {

    anchors.fill: parent

    TableViewColumn {title: "1"; role: "one"; width: 70 }
    TableViewColumn {title: "2"; role: "two"; width: 70   }
    TableViewColumn {title: "3"; role: "three"; width: 70 }

    model: theModel

}

How can we achieve a similar result in Qt Quick 2 if there is no more TableViewColumn for the TableView ?

Since Qt 5.12 you can use TableView QML type. But to have everything you want you need to include Qt.labs.qmlmodels . It all is available in Qt 5.15 (use online installer ).

Actual implementation will hardly depend on your requirements, but here is an example of how it could be done.

  • Let's say you are going to use TableView to show some data you have in JSON format. In this case TableModel will be a perfect fit, since it is designed to work with JavaScript/JSON data, where each row is a simple key-pair object without requiring the creation of a custom QAbstractTableModel subclass in C++.

  • You need to declare what columns do you need to have in your model by using TableModelColumn , eg: TableModelColumn { display: "checked" } .

  • For loading real data into model use its rows property; data should be in the form of an array of rows, eg:

rows: [
        // Each property is one cell/column.
        {
          checked: false,
          amount: 1,
          type: "Apple",
          price: 1.50
        },
        {
          checked: true,
          amount: 4,
          type: "Orange",
          price: 2.50
        },
        ...
      ]
  • Most interesting part here is appliance of delegate -- here it be DelegateChooser , since it allows a view to use different delegates for different types of items in the model. So here you can do almost everything to tweak your cells. Eg: you can use ProgressBar component as your delegate for a cell:
DelegateChoice {
  column: 1
  delegate: ProgressBar {
    enabled: false
    width: 100
    from: 0.0
    to: 10.0
    value: model.display
  }
}

As result you could easily get this application entirely in QML (whiteout need to use C++ and/or old QtQuick.Controls):

应用示例

Please refer to this repository to get full application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM