TableModel

From Qt Wiki
Jump to navigation Jump to search

TableModel provides a QAbstractTableModel that can be used in QML with TableView.

Requirements

#1

Allow different data format/structure for rows; need to be flexible. For example, it should be possible to specify several roles per column, as QAbstractTableModel supports this:

   model: TableModel {
       // Each row is one type of fruit that can be ordered
       rows: [
           [
               // Each object (line) is one cell/column,
               // and each property in that object is a role.
               { checked: false, checkable: true },
               { amount: 1 },
               { fruitType: "Apple" },
               { fruitName: "Granny Smith" },
               { fruitPrice: 1.50 }
           ],
           [
               { checked: true, checkable: true },
               { amount: 4 },
               { fruitType: "Orange" },
               { fruitName: "Navel" },
               { fruitPrice: 2.50 }
           ]
       ]
   }

In addition, it should be possible to use a simple object for a row, as this seems to be common with web APIs:

   [
       {
           "driverId":"fisichella",
           "code":"FIS",
           "url":"http://en.wikipedia.org/wiki/Giancarlo_Fisichella",
           "givenName":"Giancarlo",
           "familyName":"Fisichella",
           "dateOfBirth":"1973-01-14",
           "nationality":"Italian"
       },
       {
           "driverId":"barrichello",
           "code":"BAR",
           "url":"http://en.wikipedia.org/wiki/Rubens_Barrichello",
           "givenName":"Rubens",
           "familyName":"Barrichello",
           "dateOfBirth":"1972-05-23",
           "nationality":"Brazilian"
       }
   ]

#2

We know we want settable rowCount + columnCount for prototyping and allowing use cases such as e.g. spreadsheets.

Solutions

Below are alternative solutions that aim to solve all of the requirements.

#1 "rows"

Current (unfinished) state as of writing can be seen here: http://code.qt.io/cgit/qt/qtdeclarative.git/tree/src/qml/types/qqmltablemodel.cpp?h=dev&id=b4ee855eb10cf9bfa44ce8e5de8f9ee6c5917764

In addition, there are some follow-up patches:

#2 No "rows"

  • We know we can't expect one data format/structure for rows; need to be flexible.
  • We know we want settable rowCount + columnCount.
  • roleDataLookPolicy (https://codereview.qt-project.org/#/c/253509/) is making things quite complex.

So:

  • Remove "rows" altogether. How the actual source JS data is stored and formatted is up to the user,
  • rowCount and columnCount would then have to always be specified so that we know how many there are.
  • "roles" allows the user to use their custom roles without us having parsed the rows data (currently we parse it up front using an expected format so that we know which roles are available):
   roles: [
       ["driverId"],
       ["code"],
       ["url"],
       ["givenName"],
       ["familyName"],
       ["dateOfBirth"],
       ["nationality"]
   ]
  • Then we call roleDataProvider() unconditionally each time data() is called for a "new" index, and store that in our own well-formatted map/hash, so we don't need to call roleDataProvider() again for that index.
  • As appendRow(), moveRow(), etc. would no longer take the row as an argument, they would need to be replaced with beginAppendRow()/endAppendRow(), etc.

An example:

   import QtQuick 2.12
   import QtQuick.Window 2.12
   import Qt.labs.qmlmodels 1.0
   Window {
       width: 400
       height: 400
       visible: true
       // pretend we got data from some web API...
       property var tableData: [
           [
               // Each object (line) is one cell/column,
               // and each property in that object is a role.
               { checked: false, checkable: true },
               { amount: 1 },
               { fruitType: "Apple" },
               { fruitName: "Granny Smith" },
               { fruitPrice: 1.50 }
           ],
           [
               { checked: true, checkable: true },
               { amount: 4 },
               { fruitType: "Orange" },
               { fruitName: "Navel" },
               { fruitPrice: 2.50 }
           ],
           [
               { checked: false, checkable: true },
               { amount: 1 },
               { fruitType: "Banana" },
               { fruitName: "Cavendish" },
               { fruitPrice: 3.50 }
           ]
       ]
       TableView {
           anchors.fill: parent
           columnSpacing: 1
           rowSpacing: 1
           boundsBehavior: Flickable.StopAtBounds
           model: TableModel {
               rowCount: tableData.length
               columnCount: roles.length
               // If there is only one role per column:
   //            roleDataProvider: function(index, role) {
   //                return tableData[index.row][role]
   //            }
               // Otherwise, handle those with more than one:
               roleDataProvider: function(index, role) {
                   var rowData = tableData[index.row]
                   switch (index.column) {
                   case 0:
                       return role === "checked" ? rowData.checked : rowData.checkable
                   default:
                       return tableData[index.row][role]
                   }
               }
               roles: [
                   ["checked", "checkable"],
                   ["fruitType"],
                   ["fruitName"],
                   ["fruitPrice"]
               ]
           }
           // delegate: ...
       }
       /*
           To append a row:
           model.beginAppendRow()
           // user code to append row to tableData
           model.endAppendRow()
       */
   }
#3 Discrete ModelColumn objects

ModelColumn is implemented similar to ListElement: it declares additional roles that the delegate can use, and what they map to.

  • A role can map to a JSON role directly
  • A role can map to a function: this idea replaces roleDataProvider, but now the function has a narrower scope, so it's less likely to need a big switch statement.  But if you want to write one big function and reuse it, you just have to declare it separatly.
  • index is special: it can be a number telling which column this declaration defines.  If omitted, the declaration applies to all columns except those where explicit declarations override it.
  • header is special: it can be a string to display in the column heading, or a function taking a column number and returning a string.  This replaces horizontalHeaderData and verticalHeaderData.
  • If any column or role that the delegate uses is left undefined, or if there are no ModelColumn declarations at all, fall back to looking up the role explicitly in the JSON data, or taking the unlabeled data from that cell (e.g. the string "Apple" in the example is an unlabeled cell datum), or taking the first labeled role (e.g. the "Granny Smith" variety is labeled data, but there is no role mapping in column 1).
	TableModel {
		ModelColumn {
			// index is omitted: this is default for all columns
			// all roles are omitted: so just look for explicit "display" or unlabeled data as necessary
			header: function(index) { return index } // by default just display the column index (0..3)
		}
		ModelColumn {
			index: 2 // override behavior in column 2
			display: "price" // when the delegate asks for "display" role, look for "price" in the JSON
			edit: "price"
			header: "Price" // a plain string to display (not a function, not a role)
		}
		ModelColumn {
			index: 4
			display: function(index, role, cellData) {
				function v(c) { return ... }
				eval(cellData["formula"]) // or whatever else is necessary
			} // this replaces the roleDataProvider declaration
			edit: "formula" // this is a role mapping: when the delegate asks for "edit" role, look for "formula" in the JSON
		}
		rows: [
			["Apple", {variety: "Granny Smith"}, {price: 1.50}, 1, {formula: "v(3) * v(2)"}],
			["Banana", {variety: "Cavendish"}, {price: 3.50}, 1, {formula: "v(3) * v(2)"}] // formula is a mini-language: only sensible to the calculation function
		]
	}