AbstractListModel rows added but QML View not being updated - qt

I have a model that have a list of MarkerItem (which is a struct).
struct MarkerItem{
enum marker_state{
marker_observation = 0,
marker_important,
marker_redundant,
marker_deleted
};
MarkerItem(const QPointF& pos, marker_state state, const QDateTime& when, const QString& label);
const QPointF& position() const;
QGeoCoordinate coordinate() const;
const QString& label() const;
marker_state state() const;
void change_state(marker_state state);
private:
QPointF _position;
marker_state _state;
QString _label;
QDateTime _when;
};
class MarkerModel : public QAbstractListModel{
Q_OBJECT
Q_PROPERTY(QGeoRoute* route READ route NOTIFY routeChanged)
public:
enum MarkerRoles {
PositionRole = Qt::UserRole + 1,
StateRole,
LabelRole
};
explicit MarkerModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
public:
QHash<int, QByteArray> roleNames() const;
private:
QList<MarkerItem*> _markers;
public:
void addMarker(MarkerItem* marker);
public:
QGeoRoute* route() const;
signals:
void routeChanged();
};
void MarkerModel::addMarker(MarkerItem *marker){
beginInsertRows(QModelIndex(), rowCount(), rowCount());
_markers.push_back(marker);
qWarning() << rowCount();
endInsertRows();
}
In my QML I have
Map {
id: map
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(22.5726, 88.3639)
zoomLevel: 14
MapItemView {
model: markerModel
delegate: markerDelegate
}
Component {
id: markerDelegate
MapQuickItem{
anchorPoint: Qt.point(2.5, 2.5)
coordinate: QtPositioning.coordinate(position.x, position.y)
zoomLevel: 0
sourceItem: Rectangle{
width: settings.marker_size;
height: settings.marker_size;
radius: settings.marker_size/2;
color: settings.marker_colors[status]
border.color: "white"
border.width: 1
}
}
}
Component{
id: polyline
MapPolyline {
line.color: black
line.width: 2
path: []
}
}
}
I am passing this model to QML view
_model->addMarker(new MarkerItem(QPointF(22.5868f, 88.4149f), MarkerItem::marker_observation, QDateTime::currentDateTime(), "1"));
_model->addMarker(new MarkerItem(QPointF(22.5391f, 88.3958f), MarkerItem::marker_observation, QDateTime::currentDateTime(), "2"));
qRegisterMetaType<MarkerModel*>("MarkerModel");
QWidget* container = QWidget::createWindowContainer(_view, this);
container->setFocusPolicy(Qt::TabFocus);
_view->engine()->rootContext()->setContextProperty("markerModel", _model);
_view->setSource(QUrl("qrc:///main.qml"));
QVBoxLayout* layout = new QVBoxLayout;
setLayout(layout);
layout->addWidget(container);
_root = _view->rootObject();
The first two points that are added before setting the model to QML context appears in the view. However when I am adding some new points (based on user input from Toolbar Action) with the addMarker function It adds the markers in the model, but view does not update
All the codes in the project is uploaded on the gist

The problem can be said that it is in your code or is in your data, what happens is that the data you are giving back is in the geographic coordinates.
If you want to keep your data you only have to change the following:
coordinate: QtPositioning.coordinate(position.y, position.x)
If you do not want to change your code, exchange the coordinates in your data.
I chose the first option and moving the map a bit I got the following:

Related

qml TableView itemdelegate not firing (using a QAbstractTableModel)

Im trying to get my first QML TableView to work in Qt 5.2 (since we are stuck on that
version right now at work) using a QAbstractTableModel on the backend.
My main issue is that for some reason the itemDelegate is never firing so
I never see anything in the View except the outline of the TableView.
I have also verified that theData_ is filled with 2 dimensional numbers
in every row/column in the constructor and I do an emit layoutChanged()
as well as an emit dataChanged() in the constructor.
I realize I have no error checking for an invalid QModelIndex in the data() call
at this time.
I also did not implement index() at all.
Also is there any need to use a ROLE here?
The data Im displaying is a single integer (as a QString) per cell, nothing more at this time.
Thanks for your help
qml:
TableView {
width: 600
height: 600
model: myModel
visible: true
itemDelegate: Rectangle {
color: "lightgray"
width: 100
height: 20
Text {
text: styleData.value
color: "black"
}
}
}
relevant code from subclassed QAbstractTableModel:
int MyModel::rowCount(const QModelIndex&) const
{
return 10;
}
int MyModel::columnCount(const QModelIndex&) const
{
return 3;
}
QVariant MyModel::data(const QModelIndex& index, int role) const
{
const int row = index.row();
const int col = index.column();
return QString("%1").arg(this->theData_[col][row]);
}
Before Qt 5.12 there was only a TableView component that belongs to Qt QuickControl 1 that only supports a list type model where each column reflects the information of a role so this is probably your problem since you have not created any TableViewColumn. On the other hand, as of >= Qt5.12, another TableView already exists, which it supports as a table type model.
mymodel.h
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractListModel>
struct Data{
int number;
QString text;
};
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
enum CustomRoles{
NumberRole = Qt::UserRole,
TextRole
};
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QHash<int, QByteArray> roleNames() const override;
private:
QList<Data> m_data;
};
#endif // MYMODEL_H
mymodel.cpp
#include "mymodel.h"
MyModel::MyModel(QObject *parent)
: QAbstractListModel(parent)
{
// for test
for(int i=0; i< 10; i++){
Data d{i, QString::number(i)};
m_data.push_back(d);
}
}
int MyModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_data.count();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if(role == NumberRole)
return m_data.at(index.row()).number;
if(role == TextRole)
return m_data.at(index.row()).text;
return QVariant();
}
QHash<int, QByteArray> MyModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[NumberRole] = "number";
roles[TextRole] = "text";
return roles;
}
main.qml
// ...
TableView {
width: 600
height: 600
model: myModel
visible: true
TableViewColumn {
role: "number"
title: "Number"
width: 100
}
TableViewColumn {
role: "text"
title: "Text"
width: 200
}
itemDelegate: Rectangle {
color: "lightgray"
width: 100
height: 20
Text {
text: styleData.value
color: "black"
}
}
}
// ...

Animating MapQuickItem in QML on position updates

I have an QAbstractListModel object that maintains a list of items to show on a map. The position of these items changes every few seconds and it is easy to calculate a pretty accurate position 60 seconds in the future. What I am trying to do is to set the item's position when it gets a new position (that part works well) and then to immediately move the item toward the calculated future position.
The code without animation looks like this and it works fine:
Component {
id: drawTarget
MapQuickItem {
id: marker
coordinate: data.coords
sourceItem: Item {
id: item
...
The data object has a property which returns the estimated position of the item 60 seconds in the future, so I tried this:
Component {
id: drawTarget
MapQuickItem {
id: marker
coordinate: data.coords
CoordinateAnimation {
id:anim
property: "coordinate"
}
onCoordinateChanged: {
anim.stop()
anim.from = data.coords
anim.to = data.coordsIn60sec
anim.duration = 60000
anim.start()
}
sourceItem: Item {
id: item
...
But although the object's position is updated properly at each position update, the animation toward the future estimated position doesn't work at all.
How would one go about doing something like this?
In its code, it makes a binding coordinate: data.coords that states that "coordinate" takes the value of "coords" but at the same time says that "coordinate" depends on the animation, isn't it contradictory? Well, it is contradictory.
The idea is not to do the binding coordinate: data.coords but to update the property only through the animation.
The following code is a workable example:
main.qml
import QtQuick 2.14
import QtQuick.Window 2.14
import QtLocation 5.6
import QtPositioning 5.6
Window {
visible: true
width: 640
height: 480
Plugin {
id: mapPlugin
name: "osm"
}
Map {
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(59.91, 10.75) // Oslo
zoomLevel: 10
MapItemView{
model: datamodel
delegate: MapQuickItem{
id: item
// begin configuration
property var position: model.position
property var nextposition: model.nextposition
onPositionChanged: restart();
onNextpositionChanged: restart();
function restart(){
anim.stop()
anim.from = position
anim.to = nextposition
anim.start()
}
CoordinateAnimation {
id: anim
target: item
duration: 60 * 1000
property: "coordinate"
}
// end of configuration
anchorPoint.x: rect.width/2
anchorPoint.y: rect.height/2
sourceItem: Rectangle{
id: rect
color: "green"
width: 10
height: 10
}
}
}
}
}
datamodel.h
#ifndef DATAMODEL_H
#define DATAMODEL_H
#include <QAbstractListModel>
#include <QGeoCoordinate>
#include <QTimer>
#include <random>
#include <QDebug>
struct Data{
QGeoCoordinate position;
QGeoCoordinate nextposition;
};
static QGeoCoordinate osloposition(59.91, 10.75); // Oslo;
class DataModel : public QAbstractListModel
{
Q_OBJECT
QList<Data> m_datas;
public:
enum PositionRoles {
PositionRole = Qt::UserRole + 1,
NextPositionRole
};
explicit DataModel(QObject *parent = nullptr)
: QAbstractListModel(parent)
{
init();
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override{
return parent.isValid() ? 0: m_datas.count();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override{
if (!index.isValid() || index.row() < 0 || index.row() >= m_datas.count())
return QVariant();
const Data &data = m_datas[index.row()];
if (role == PositionRole)
return QVariant::fromValue(data.position);
else if (role == NextPositionRole)
return QVariant::fromValue(data.nextposition);
return QVariant();
}
QHash<int, QByteArray> roleNames() const override{
QHash<int, QByteArray> roles;
roles[PositionRole] = "position";
roles[NextPositionRole] = "nextposition";
return roles;
}
private:
void init(){
for(int i=0; i< 10; ++i){
Data data;
data.position = osloposition;;
data.nextposition = data.position;
m_datas << data;
}
QTimer *timer = new QTimer(this);
QObject::connect(timer, &QTimer::timeout, this, &DataModel::updateData);
timer->start(60 * 1000);
updateData();
}
void updateData(){
qDebug() << __PRETTY_FUNCTION__;
static std::default_random_engine e;
static std::uniform_real_distribution<> dis(-.1, .1);
for(int i=0; i < m_datas.count(); ++i){
Data & data = m_datas[i];
QModelIndex ix = index(i);
data.position = data.nextposition;
data.nextposition = QGeoCoordinate(osloposition.latitude() + dis(e),
osloposition.longitude() + dis(e));
Q_EMIT dataChanged(ix, ix, {PositionRole, NextPositionRole});
}
}
};
#endif // DATAMODEL_H
In the following link is the complete example

Is this the Minimum Viable TreeView Model in QML?

I'm making a folding list of three items: "Hey", "Whats", and "Up?". I want to put it into a tree view. I know this list will only ever contain these three items. Therefore, I would like to know how to "nest" these items together.
I know there are implementation for agile systems that support adding and removing parent/child objects, finding indexes... powerful models. However, I literally only need to display these items in an expandable/collapsable view. Here is what I've read through relating to C++ and QAbstractItemModels:
QML Treeview
QML QAbstractItemModel
This Question by My_Cat_Jessica
This question by kavaliero which was based on:
This 'working' example by Qt themselves (Doesn't actually work for TreeView. Works for QTreeView though!)
Here is the simplest viable code to implement a treeview with model:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: mywindow
visible: true
width: 640
height: 480
TreeView {
id: treeview
anchors.fill: parent
TableViewColumn {
title: "Phrase"
role: "phrase"
}
model: phraseModel
}
ListModel {
id: phraseModel
ListElement { phrase: "Hey"; }
ListElement { phrase: "What's"; }
ListElement { phrase: "Up?"; }
}
}
I would like for the output to result in a nested stack like this:
Hey
What's
Up?
But I am getting everything in a single column all aligned with each other:
Hey
What's
Up?
I know I haven't assigned parents, and I'm not entirely sure how to do that - But I'm not even sure if that's what needs done to this code. So my question is this: What's the final step missing to stack these three elements into an expandable/collapsible view?
There is no native QML model that can use the TreeView, so I have implemented a model that tries to be generic:
TreeElement
// treeelement.h
#ifndef TreeElement_H
#define TreeElement_H
#include <QObject>
#include <QQmlListProperty>
class TreeElement : public QObject
{
Q_OBJECT
public:
Q_PROPERTY(QQmlListProperty<TreeElement> items READ items)
Q_CLASSINFO("DefaultProperty", "items")
TreeElement(QObject *parent = Q_NULLPTR);
Q_INVOKABLE TreeElement *parentItem() const;
bool insertItem(TreeElement *item, int pos = -1);
QQmlListProperty<TreeElement> items();
TreeElement *child(int index) const;
void clear();
Q_INVOKABLE int pos() const;
Q_INVOKABLE int count() const;
private:
static void appendElement(QQmlListProperty<TreeElement> *property, TreeElement *value);
static int countElement(QQmlListProperty<TreeElement> *property);
static void clearElement(QQmlListProperty<TreeElement> *property);
static TreeElement *atElement(QQmlListProperty<TreeElement> *property, int index);
QList<TreeElement *> m_childs;
TreeElement *m_parent;
};
#endif // TreeElement_H
// treeelement.cpp
#include "treeelement.h"
TreeElement::TreeElement(QObject *parent) :
QObject(parent),
m_parent(nullptr) {}
TreeElement *TreeElement::parentItem() const{
return m_parent;
}
QQmlListProperty<TreeElement> TreeElement::items(){
return QQmlListProperty<TreeElement> (this,
this,
&TreeElement::appendElement,
&TreeElement::countElement,
&TreeElement::atElement,
&TreeElement::clearElement);
}
TreeElement *TreeElement::child(int index) const{
if(index < 0 || index >= m_childs.length())
return nullptr;
return m_childs.at(index);
}
void TreeElement::clear(){
qDeleteAll(m_childs);
m_childs.clear();
}
bool TreeElement::insertItem(TreeElement *item, int pos){
if(pos > m_childs.count())
return false;
if(pos < 0)
pos = m_childs.count();
item->m_parent = this;
item->setParent(this);
m_childs.insert(pos, item);
return true;
}
int TreeElement::pos() const{
TreeElement *parent = parentItem();
if(parent)
return parent->m_childs.indexOf(const_cast<TreeElement *>(this));
return 0;
}
int TreeElement::count() const{
return m_childs.size();
}
void TreeElement::appendElement(QQmlListProperty<TreeElement> *property, TreeElement *value){
TreeElement *parent = qobject_cast<TreeElement *>(property->object);
parent->insertItem(value);
}
int TreeElement::countElement(QQmlListProperty<TreeElement> *property){
TreeElement *parent = qobject_cast<TreeElement *>(property->object);
return parent->count();
}
void TreeElement::clearElement(QQmlListProperty<TreeElement> *property){
TreeElement *parent = qobject_cast<TreeElement *>(property->object);
parent->clear();
}
TreeElement *TreeElement::atElement(QQmlListProperty<TreeElement> *property, int index){
TreeElement *parent = qobject_cast<TreeElement *>(property->object);
if(index < 0 || index >= parent->count())
return nullptr;
return parent->child(index);
}
TreeModel
// treemodel.h
#ifndef TreeModel_H
#define TreeModel_H
#include <QAbstractItemModel>
#include <QQmlListProperty>
class TreeElement;
class TreeModel : public QAbstractItemModel
{
Q_OBJECT
public:
Q_PROPERTY(QQmlListProperty<TreeElement> items READ items)
Q_PROPERTY(QVariantList roles READ roles WRITE setRoles NOTIFY rolesChanged)
Q_CLASSINFO("DefaultProperty", "items")
TreeModel(QObject *parent = Q_NULLPTR);
~TreeModel() override;
QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE;
QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE;
Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
QModelIndex parent(const QModelIndex &index) const Q_DECL_OVERRIDE;
int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE;
QQmlListProperty<TreeElement> items();
QVariantList roles() const;
void setRoles(const QVariantList &roles);
Q_INVOKABLE QModelIndex indexFromElement(TreeElement *item);
Q_INVOKABLE bool insertElement(TreeElement *item, const QModelIndex &parent = QModelIndex(), int pos = -1);
TreeElement *elementFromIndex(const QModelIndex &index) const;
private:
TreeElement *m_root;
QHash<int, QByteArray> m_roles;
signals:
void rolesChanged();
};
#endif // TreeModel_H
// treemodel.cpp
#include "treemodel.h"
#include "treeelement.h"
TreeModel::TreeModel(QObject *parent) :
QAbstractItemModel(parent){
m_root = new TreeElement;
}
TreeModel::~TreeModel(){
delete m_root;
}
QHash<int, QByteArray> TreeModel::roleNames() const{
return m_roles;
}
QVariant TreeModel::data(const QModelIndex &index, int role) const{
if (!index.isValid())
return QVariant();
TreeElement *item = static_cast<TreeElement*>(index.internalPointer());
QByteArray roleName = m_roles[role];
QVariant name = item->property(roleName.data());
return name;
}
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const{
if (!index.isValid())
return nullptr;
return QAbstractItemModel::flags(index);
}
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const{
if (!hasIndex(row, column, parent))
return QModelIndex();
TreeElement *parentItem = elementFromIndex(parent);
TreeElement *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex TreeModel::parent(const QModelIndex &index) const{
if (!index.isValid())
return QModelIndex();
TreeElement *childItem = static_cast<TreeElement*>(index.internalPointer());
TreeElement *parentItem = static_cast<TreeElement *>(childItem->parentItem());
if (parentItem == m_root)
return QModelIndex();
return createIndex(parentItem->pos(), 0, parentItem);
}
int TreeModel::rowCount(const QModelIndex &parent) const{
if (parent.column() > 0)
return 0;
TreeElement *parentItem = elementFromIndex(parent);
return parentItem->count();
}
int TreeModel::columnCount(const QModelIndex &parent) const{
Q_UNUSED(parent)
return 1;
}
QQmlListProperty<TreeElement> TreeModel::items(){
return m_root->items();
}
QVariantList TreeModel::roles() const{
QVariantList list;
QHashIterator<int, QByteArray> i(m_roles);
while (i.hasNext()) {
i.next();
list.append(i.value());
}
return list;
}
void TreeModel::setRoles(const QVariantList &roles){
static int nextRole = Qt::UserRole + 1;
for(QVariant role : roles) {
m_roles.insert(nextRole, role.toByteArray());
nextRole ++;
}
emit rolesChanged();
}
QModelIndex TreeModel::indexFromElement(TreeElement *item){
QVector<int> positions;
QModelIndex result;
if(item) {
do{
int pos = item->pos();
positions.append(pos);
item = item->parentItem();
} while(item != nullptr);
for (int i = positions.size() - 2; i >= 0 ; i--)
result = index(positions[i], 0, result);
}
return result;
}
bool TreeModel::insertElement(TreeElement *item, const QModelIndex &parent, int pos){
TreeElement *parentElement = elementFromIndex(parent);
if(pos >= parentElement->count())
return false;
if(pos < 0)
pos = parentElement->count();
beginInsertRows(parent, pos, pos);
bool retValue = parentElement->insertItem(item, pos);
endInsertRows();
return retValue;
}
TreeElement *TreeModel::elementFromIndex(const QModelIndex &index) const{
if(index.isValid())
return static_cast<TreeElement *>(index.internalPointer());
return m_root;
}
main.cpp
#include "treemodel.h"
#include "treeelement.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
static void registertypes(){
qmlRegisterType<TreeElement>("foo", 1, 0, "TreeElement");
qmlRegisterType<TreeModel>("foo", 1, 0, "TreeModel");
}
Q_COREAPP_STARTUP_FUNCTION(registertypes)
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
import foo 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TreeModel {
id: treemodel
roles: ["phrase"]
TreeElement{
property string phrase: "Hey"
TreeElement{
property string phrase: "What's"
TreeElement{
property string phrase: "Up?"
}
}
}
}
TreeView {
anchors.fill: parent
model: treemodel
TableViewColumn {
title: "Name"
role: "phrase"
width: 200
}
}
}
Output:
The complete example you find here
I created a collapsible frame in QML (a group box with a title and a content). If you are sure that you will never change the structure, you can use for your purpose:
I simplified the code by removing the useless parts (animations, decorations, etc.). So the code below could be improved. But, I kept the idea:
// CollapsibleGroupBox.qml
Item {
property alias contentItem: content.contentItem;
property string title: ""
Item {
id: titleBar
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
height: 30
Row {
anchors.fill: parent
CheckBox {
Layout.alignment: Qt.AlignLeft
id: expand
checked: true;
}
Text {
Layout.alignment: Qt.AlignLeft
text: title
}
}
}
Pane {
anchors.left: parent.left
anchors.right: parent.right
anchors.top: titleBar.bottom
anchors.bottom: parent.bottom
topPadding: 0
visible: expand.checked
id: content
}
}
// Main.qml
Item {
height: 500
width: 500
CollapsibleGroupBox {
anchors.fill: parent
title: "Hey!"
contentItem: CollapsibleGroupBox {
title: "What's"
contentItem: CollapsibleGroupBox {
title: "up?"
}
}
}
}
You will get:
You can replace the checkbox by a MouseArea, also.
I've also created a model that only uses QML components:
import QtQuick 2.9
import QtQuick.Window 2.2
import UISettings 1.0
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls 1.4 as SV
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Flickable {
id: flick
anchors.fill: parent
clip: true
contentHeight: col.implicitHeight
property var mymodel: {
"animals": {
"big": {
"land": "elephants",
"water": "whales"
},
"small": {
"land": "mice",
"water": "fish"
}
},
"plants": {
"trees": "evergreens"
}
}
Column {
id: col
Component.onCompleted: componentListView.createObject(this, {"objmodel":flick.mymodel});
}
Component {
id: componentListView
Repeater {
id: repeater
property var objmodel: ({})
model: Object.keys(objmodel)
ColumnLayout {
Layout.leftMargin: 50
Button {
property var sprite: null
text: modelData
onClicked: {
if(sprite === null) {
if(typeof objmodel[modelData] === 'object')
sprite = componentListView.createObject(parent, {"objmodel":objmodel[modelData]});
}
else
sprite.destroy()
}
}
}
}
}
}
}

Qt/QML How to return QList<T> collection from virtual data metod from QAbstractListModel

I want to summarize What to do. I have an DataObject class which have members:
QString first;QString last;QList<SubObject*> m_sublist;
I am using QAbstractListModel to this. I can refer first and last to listview but I can't refer to like m_sublist[0].lesson. It gives me error like:
Cannot read property 'lesson' of undefined.
My code:
dataobject.h
class SubObject :public QObject
{
Q_OBJECT
public:
SubObject(const QString &lesson,QObject *parent = 0);
const QString lesson;
private:
// bool operator==(const SubObject* &other) const {
// return other->lesson == lesson;
// }
};
class DataObject :public QObject{
Q_OBJECT
public:
DataObject(const QString &firstName,
const QString &lastName,
const QList<SubObject*> &sublist);
QString first;
QString last;
QList<SubObject*> m_sublist;
};
simplelistmodel.h
class SimpleListModel : public QAbstractListModel {
Q_OBJECT
public:
SimpleListModel(QObject *parent=0);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QHash<int,QByteArray> roleNames() const { return m_roleNames; }
private:
// Q_DISABLE_COPY(SimpleListModel);
QList<DataObject*> m_items;
static const int FirstNameRole;
static const int LastNameRole;
static const int SubListRole;
QHash<int, QByteArray> m_roleNames;
};
simplelistmodel.cpp
const int SimpleListModel::FirstNameRole = Qt::UserRole + 1;
const int SimpleListModel::LastNameRole = Qt::UserRole + 2;
const int SimpleListModel::SubListRole = Qt::UserRole + 3;
SimpleListModel::SimpleListModel(QObject *parent) :
QAbstractListModel(parent) {
// Create dummy data for the list
QList<SubObject*> mysublist;
mysublist.append(new SubObject("MAT"));
mysublist.append(new SubObject("FEN"));
DataObject *first = new DataObject(QString("Arthur"), QString("Dent"),mysublist);
DataObject *second = new DataObject(QString("Ford"), QString("Prefect"),mysublist);
DataObject *third = new DataObject(QString("Zaphod"), QString("Beeblebrox"),mysublist);
m_items.append(first);
m_items.append(second);
m_items.append(third);
// m_roleNames = SimpleListModel::roleNames();
m_roleNames.insert(FirstNameRole, QByteArray("firstName"));
m_roleNames.insert(LastNameRole, QByteArray("lastName"));
m_roleNames.insert(SubListRole, QByteArray("subList"));
}
int SimpleListModel::rowCount(const QModelIndex &) const {
return m_items.size();
}
QVariant SimpleListModel::data(const QModelIndex &index,
int role) const {
if (!index.isValid())
return QVariant(); // Return Null variant if index is invalid
if (index.row() > (m_items.size()-1) )
return QVariant();
DataObject *dobj = m_items.at(index.row());
switch (role) {
case Qt::DisplayRole: // The default display role now displays the first name as well
case FirstNameRole:
return QVariant::fromValue(dobj->first);
case LastNameRole:
return QVariant::fromValue(dobj->last);
case SubListRole:
return QVariant::fromValue(dobj->m_sublist);
default:
return QVariant();
}
}
main.cpp
int main(int argc, char *argv[]) {
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
SimpleListModel model;
QQmlContext *classContext = engine.rootContext();
classContext->setContextProperty("absmodel",&model);
engine.load(QUrl(QStringLiteral("qrc:/myuiscript.qml")));
return app.exec(); }
myuiscript.qml
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
id: bgRect
width: 200
height: 200
color: "black"
visible: true
ListView {
id: myListView
anchors.fill: parent
delegate: myDelegate
model: absmodel
}
Component {
id: myDelegate
Item {
width: 200
height: 40
Rectangle {
anchors.fill: parent
anchors.margins: 2
radius: 5
color: "lightsteelblue"
Row {
anchors.verticalCenter: parent.verticalCenter
Text {
text: firstName
color: "black"
font.bold: true
}
Text {
text: subList[0].lesson
color: "black"
}
}
}
}
}
}
I can't find any solution. Virtual data model returns single type of objects. FirsName is a string. I cant refer listview delegate like firstName(rolename). Also LastName is refered like lastName(rolename). But I can't refer subList(roleNames) like sublist[0].lesson.
My target is very simple. I want to refer single type (int,QString ....) to text in delegate by using rolename. I can't refer collection type(QList<SubObject*>) to text in delegate using rolename(subList[0].lesson). How to achive them?
Let's fix it step by step. This line text: subList[0].lesson in QML produce the error message
TypeError: Cannot read property 'lesson' of undefined
That means subList[0] is an undefined object and QML engine cannot read any property, including lesson, from this object. In fact, subList returned from model is a well-defined QList<SubObject*> object, but not subList[0] since QList<SubObject*> is not a QML list. To correctly pass a list from C++ to QML, return a QVariantList instead of QList.
//class DataObject
DataObject(const QString &firstName,
const QString &lastName,
const QVariantList &sublist);
QVariantList m_sublist; //use QVariantList instead of QList<SubObject*>
//---
//SimpleListModel::SimpleListModel
QVariantList mysublist; //use QVariantList instead of QList<SubObject*>
mysublist.append(QVariant::fromValue(new SubObject("MAT", this))); //remember parent
mysublist.append(QVariant::fromValue(new SubObject("FEN", this)));
//...
Now, subList[0] can be accessed in QML, but not subList[0].lesson. To access properties in a C++ class, explicitly define the property with Q_PROPERTY macro.
class SubObject :public QObject
{
Q_OBJECT
Q_PROPERTY(QString lesson READ getLesson NOTIFY lessonChanged)
public:
SubObject(const QString &lesson,QObject *parent = 0):
QObject(parent), m_lesson(lesson){;}
QString getLesson() const {return m_lesson;}
signals:
void lessonChanged();
private:
QString m_lesson;
};
And the QML code works now.

QtQuick TableView not working with C++-QAbstractTableModel

I am trying to get the Qt model/view-architecture working with a QML-View, but for whatever reason it is only partially working.
What works:
rowCount
data
roleNames
Not working:
columnCount (the method is called, but seems to have no effect, as long is it is > 0)
headerData (is this actually supposed to set the column headers? All examples set the headers in QML)
flags
setData
What I am trying to do (for some weeks already), is to create a simple ApplicationView with a TableView and a C++-model, which is editable by the view.
Right now only a whole row is selectable, not a single cell. The table data doesn't seem to be editable at all. Can anyone give me a hint?
main.qml
import QtQuick 2.3
import QtQuick.Controls 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TableView {
model: theModel
TableViewColumn {
role: "nameRole"
width: 75
}
TableViewColumn {
role: "ageRole"
width: 50
}
}
}
ModelItem.hpp
#ifndef MODELITEM
#define MODELITEM
#include <QString>
struct ModelItem {
ModelItem(QString name_, int age_)
: name(name_), age(age_) {}
QString name;
int age;
};
#endif // MODELITEM
TableModel.hpp
#ifndef TABLEMODEL_HPP
#define TABLEMODEL_HPP
#include <QAbstractTableModel>
#include "ModelItem.hpp"
class TableModel : public QAbstractTableModel
{
Q_OBJECT
public:
TableModel(QObject *parent = 0);
//works
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
//does not work
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
QHash<int, QByteArray> roleNames() const;
enum Roles {
NameRole = Qt::UserRole + 1,
AgeRole
};
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
private:
QList<ModelItem*> items;
};
#endif // TABLEMODEL_HPP
TableModel.cpp
#include "TableModel.hpp"
TableModel::TableModel(QObject *parent)
: QAbstractTableModel(parent) {
items.append(new ModelItem("Hugo",33));
items.append(new ModelItem("Egon",34));
items.append(new ModelItem("Balder",66));
qDebug("TableModel initialisiert");
}
int TableModel::columnCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
qDebug("columnCount");
return 2;
}
int TableModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
qDebug("rowCount");
return items.count();
}
QVariant TableModel::data(const QModelIndex &index, int role) const {
qDebug("data");
switch (role) {
case NameRole: return items[index.row()]->name;
case AgeRole: return items[index.row()]->age;
}
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
qDebug("headerData");
switch (role) {
case NameRole: return "1";
case AgeRole: return "2";
};
return QVariant();
}
QHash<int, QByteArray> TableModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[NameRole] = "nameRole";
roles[AgeRole] = "ageRole";
qDebug("roleNames initialised");
return roles;
}
Qt::ItemFlags TableModel::flags(const QModelIndex &index) const {
qDebug("--flags called--");
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
bool TableModel::setData(const QModelIndex &index, const QVariant &value, int role) {
qDebug("setData called");
switch (role) {
case NameRole: items[index.row()]->name = value.toString();
case AgeRole: items[index.row()]->age = value.toInt();
}
emit dataChanged(index, index);
return true;
}
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "TableModel.hpp"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
TableModel model;
engine.rootContext()->setContextProperty("theModel", &model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
columnCount and rowCount called in QAbstractItemModel::index method, which is called by TableView before data method.
QModelIndex QAbstractTableModel::index(int row, int column, const QModelIndex &parent) const
{
return hasIndex(row, column, parent) ? createIndex(row, column, 0) : QModelIndex();
}
bool QAbstractItemModel::hasIndex(int row, int column, const QModelIndex &parent) const
{
if (row < 0 || column < 0)
return false;
return row < rowCount(parent) && column < columnCount(parent);
}
columnCount has no effect, as long is it is > 0, because TableView called the index method with column always equal to 0.
headerData and flags did not affect the QML TableView. You can only set the headers on the QML side. To create an editable TableView, you should implement your custom itemDelegate
main.qml
ApplicationWindow {
visible: true
id: root
Component {
id: editableDelegate
Item {
Text {
width: parent.width
anchors.margins: 4
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
elide: styleData.elideMode
text: styleData.value !== undefined ? styleData.value : ""
color: styleData.textColor
visible: !styleData.selected
}
Loader {
id: loaderEditor
anchors.fill: parent
anchors.margins: 4
Connections {
target: loaderEditor.item
onEditingFinished: {
theModel.setData(styleData.row, styleData.column, loaderEditor.item.text)
}
}
sourceComponent: styleData.selected ? editor : null
Component {
id: editor
TextInput {
id: textinput
color: styleData.textColor
text: styleData.value
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: textinput.forceActiveFocus()
}
}
}
}
}
}
TableView {
id: table
anchors.fill: parent
model: theModel
itemDelegate: editableDelegate;
TableViewColumn {
role: "nameRole"
width: 75
title: "name"
}
TableViewColumn {
role: "ageRole"
width: 50
title: "age"
}
}
}
To apply the changes to your model, you should implement the setData method, like this:
TableModel.h
bool setData(const QModelIndex &index, const QVariant &value, int role) {
switch (role) {
case NameRole: items[index.row()]->name = value.toString(); break;
case AgeRole: items[index.row()]->age = value.toInt(); break;
}
emit dataChanged(index, index);
return true;
}
Q_INVOKABLE bool setData(int row, int column, const QVariant value)
{
int role = Qt::UserRole + 1 + column;
return setData(index(row,0), value, role);
}
The above answer covers things nicely. I just want to add a couple of notes:
in QML you can simply do model.role = value within an item delegate instead of having to call setData() by hand
several QAbstractItemModel methods, including setData(), have been made Q_INVOKABLE in Qt 5.5: https://codereview.qt-project.org/#/c/107171/

Resources