How to create a TableView in QML
-
Hi.
I just switched from Qt Widget to Qt Quick.
how do I create a TableView like in Excel but lightweight, I've been using Spreadsheet but it's quite heavy what's more when setting values it makes the application crash. is there a lighter option?Thanks ^_^
-
in fact you need two structures : one core structure containing all the data, called the model, and a UI component displaying the data from the model. It is bit more complex and time consuming to setup than an excel/libreoffice spreadsheet, but much more lightweight and offers you more control and more protection on how data are displayed or edited, which cells are editable.
creating a view in
TableView { id: tableView anchors.fill: parent // or whatever anchoring/positionning/layout you want model: yourTableModel // should be declared nearby }
Please note that TableView on it's own doesn't provide horizontal and vertical headers, you have to add VerticalHeaderView and HorizontalHeaderView manually.
https://doc.qt.io/qt-6/qml-qtquick-controls-verticalheaderview.htmlfor the model, you have two options :
- either you subclass QAbstractTableModel, adding a QML_ELEMENT macro after Q_OBJECT, and declaring those source files in a qt_add_qml_module directive in CMakeLists.txt The TableView documentation provides a minimal example of a model that can be used in a QML view : https://doc.qt.io/qt-6/qml-qtquick-tableview.html
- or you can use the ListModel QML element if your model isn't much complex.
Option one is usually advised for production. Option two is often used by UI dev to supply a sample model to work on the view itself.