How to delete row from TableView properly - c++

I'm using Qt 5.15.0 on Manjaro.
I have a table I created with TableView in qml.
I can delete a row with right click on the Id field like this:
The deletion etc works but I get these errors in qml:
The method for delete rows looks like this in main.qml:
function deleteRowFromDatabase(row) {
console.log("before" + model.countOfRows())
if (!model.removeEntry(row)) {
console.log(qsTr("remove row %1 failed").arg(row))
}
model = QuestionsProxyModel
console.log("after" + model.countOfRows())
}
The error point to the delegate row of id in main.qml
DelegateChoice {
column: 0
delegate: QuestionIdDelegate {
id: questionIdDelegate
width: tableView.columnWidthProvider(column)
text: model.id /// this is undefined
row: model.row
Component.onCompleted: {
questionIdDelegate.markForDelete.connect(
tableView.deleteRowFromDatabase)
}
}
}
Removing of the rows is implemented from C++ In a class derrived from QIdentityProxyModel in questionsproxmodel.h:
bool QuestionsProxyModel::removeEntry(int row)
{
return removeRows(row, 1);
}
This model takes a class QuestionSqlTableModel derrived from QSqlTableModel as a source model
The remove rows is implemented like this in questionssqltablemodel.qml:
bool QuestionSqlTableModel::removeRows(int row, int count,
const QModelIndex &parent)
{
auto result = QSqlTableModel::removeRows(row, count, parent);
if (result) {
select(); // row is not deleted from sql database until select is called
}
return result;
}
From my understanding the countOfRows of the model gets updated only after the select() is called so I assume between QSqlTableModel::removeRows and select the TableView reads one more time with the non existing row and causes these errors in QML. How can that be prevented?
Full Source code to try it out:
main.cpp:
#include <QDebug>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QFile>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include "questionsproxymodel.h"
#include "questionsqltablemodel.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QUrl dbUrl{"file:///home/sandro/Desktop/test.db"};
auto exists = QFile::exists(dbUrl.toLocalFile());
auto db = QSqlDatabase::addDatabase("QSQLITE", "DBConnection");
db.setDatabaseName(dbUrl.toLocalFile());
db.open();
if (!exists) {
const QString questionTableName = "questions";
QSqlQuery query{db};
query.exec("CREATE TABLE " + questionTableName +
" ("
"id INTEGER PRIMARY KEY AUTOINCREMENT)");
}
QScopedPointer<QuestionSqlTableModel> questionSqlTableModel(
new QuestionSqlTableModel(nullptr, db));
QScopedPointer<QuestionsProxyModel> questionsProxyModel{
new QuestionsProxyModel};
questionsProxyModel->setSourceModel(questionSqlTableModel.get());
if (!exists) {
for (int i = 0; i < 10; ++i) {
questionsProxyModel->addNewEntry();
}
}
QQmlApplicationEngine engine;
qmlRegisterSingletonInstance<QuestionsProxyModel>(
"QuestionsProxyModels", 1, 0, "QuestionsProxyModel",
questionsProxyModel.get());
const QUrl url(QStringLiteral("qrc:/qml/main.qml"));
engine.load(url);
return app.exec();
}
questionssqltablemodel.h
#include <QSqlTableModel>
class QuestionSqlTableModel : public QSqlTableModel {
Q_OBJECT
public:
explicit QuestionSqlTableModel(QObject *parent = nullptr,
const QSqlDatabase &db = QSqlDatabase());
bool removeRows(int row, int count, const QModelIndex &parent) override;
};
questionssqltablemodel.cpp
#include "questionsqltablemodel.h"
#include <QBuffer>
#include <QDebug>
#include <QPixmap>
#include <QSqlError>
#include <QSqlField>
#include <QSqlRecord>
#include <QSqlRelationalDelegate>
QuestionSqlTableModel::QuestionSqlTableModel(QObject *parent,
const QSqlDatabase &db)
: QSqlTableModel{parent, db}
{
setTable("questions");
setSort(0, Qt::AscendingOrder);
if (!select()) {
qDebug() << "QuestionSqlTableModel: Select table questions failed";
}
setEditStrategy(EditStrategy::OnFieldChange);
}
bool QuestionSqlTableModel::removeRows(int row, int count,
const QModelIndex &parent)
{
auto result = QSqlTableModel::removeRows(row, count, parent);
if (result) {
select(); // row is not deleted from sql database until select is called
}
return result;
}
questionsproxymodel.h:
#include <QIdentityProxyModel>
#include <QObject>
class QuestionsProxyModel : public QIdentityProxyModel {
Q_OBJECT
enum questionRoles {
idRole = Qt::UserRole + 1,
};
public:
QuestionsProxyModel(QObject *parent = nullptr);
QHash<int, QByteArray> roleNames() const override;
Q_INVOKABLE QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole) override;
bool addNewEntry();
Q_INVOKABLE bool removeEntry(int row);
Q_INVOKABLE int countOfRows() const;
private:
QModelIndex mapIndex(const QModelIndex &source, int role) const;
};
questionsproxymodel.h:
#include "questionsproxymodel.h"
#include <QBuffer>
#include <QDebug>
#include <QPixmap>
#include <QByteArray>
#include <QSqlError>
#include <QSqlTableModel>
QuestionsProxyModel::QuestionsProxyModel(QObject *parent)
: QIdentityProxyModel(parent)
{
}
QHash<int, QByteArray> QuestionsProxyModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[idRole] = "id";
return roles;
}
QVariant QuestionsProxyModel::data(const QModelIndex &index, int role) const
{
QModelIndex newIndex = mapIndex(index, role);
if (role == idRole) {
return QIdentityProxyModel::data(newIndex, Qt::DisplayRole);
}
return QIdentityProxyModel::data(newIndex, role);
}
bool QuestionsProxyModel::setData(const QModelIndex &index,
const QVariant &value, int role)
{
QModelIndex newIndex = mapIndex(index, role);
if (role == idRole) {
return QIdentityProxyModel::setData(newIndex, value, Qt::EditRole);
}
return QIdentityProxyModel::setData(newIndex, value, role);
}
bool QuestionsProxyModel::addNewEntry()
{
auto newRow = rowCount();
if (!insertRows(newRow, 1)) {
return false;
}
if (!setData(createIndex(newRow, 0), newRow + 1)) {
removeRows(newRow, 1);
return false;
}
auto sqlModel = qobject_cast<QSqlTableModel *>(sourceModel());
return sqlModel->submit();
}
bool QuestionsProxyModel::removeEntry(int row)
{
return removeRows(row, 1);
}
int QuestionsProxyModel::countOfRows() const
{
return rowCount();
}
QModelIndex QuestionsProxyModel::mapIndex(const QModelIndex &source,
int role) const
{
switch (role) {
case idRole:
return createIndex(source.row(), 0);
}
return source;
}
main.qml
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Window 2.15
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls.Material 2.15
import QuestionsProxyModels 1.0
ApplicationWindow {
id: root
visible: true
width: 1460
height: 800
TableView {
id: tableView
width: parent.width
anchors.fill: parent
boundsBehavior: Flickable.StopAtBounds
reuseItems: true
clip: true
property var columnWidths: [60]
columnWidthProvider: function (column) {
return columnWidths[column]
}
model: QuestionsProxyModel
delegate: DelegateChooser {
id: chooser
DelegateChoice {
column: 0
delegate: QuestionIdDelegate {
id: questionIdDelegate
width: tableView.columnWidthProvider(column)
text: model.id
row: model.row
Component.onCompleted: {
questionIdDelegate.markForDelete.connect(
tableView.deleteRowFromDatabase)
}
}
}
}
ScrollBar.vertical: ScrollBar {}
function deleteRowFromDatabase(row) {
console.log("before" + model.countOfRows())
if (!model.removeEntry(row)) {
console.log(qsTr("remove row %1 failed").arg(row))
}
model = QuestionsProxyModel
console.log("after" + model.countOfRows())
}
}
}
QuestionIdDelegate.qml:
import QtQuick 2.15
import QtQuick.Controls 2.15
TextField {
property int row
signal markForDelete(int row)
id: root
implicitHeight: 100
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
readOnly: true
background: Frame {}
MouseArea {
id: mouseArea
anchors.fill: parent
acceptedButtons: Qt.RightButton
onClicked: {
eraseContextMenu.popup(root, 0, mouseArea.mouseY + 10)
}
}
Menu {
id: eraseContextMenu
y: root.y
MenuItem {
text: qsTr("Delete entry")
onTriggered: {
eraseDialog.open()
eraseContextMenu.close()
}
}
MenuItem {
text: qsTr("Cancel")
onTriggered: {
eraseContextMenu.close()
}
}
}
Dialog {
id: eraseDialog
title: qsTr("Delete database entry")
modal: true
focus: true
contentItem: Label {
id: label
text: qsTr("Do you really want to erase the entry with id %1?").arg(
root.text)
}
onAccepted: {
markForDelete(root.row)
}
standardButtons: Dialog.Ok | Dialog.Cancel
}
}
.pro:
QT += quick
QT += quickcontrols2
QT += sql
CONFIG += c++17
DEFINES += QT_DEPRECATED_WARNINGS
HEADERS += \
questionsproxymodel.h \
questionsqltablemodel.h
SOURCES += \
main.cpp \
questionsproxymodel.cpp \
questionsqltablemodel.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
edit:
The answer solves the error stated above. However I detected another problem with the code.
If I delete the row 1 and then the row 2 my output looks like this:
This binding loop error points Dialog in QuestionsIDDelegate:
Dialog {
id: eraseDialog
title: qsTr("Delete database entry")
modal: true
focus: true
contentItem: Label {
id: label
text: qsTr("Do you really want to erase the entry with id %1?").arg(
root.text)
}
onAccepted: {
markForDelete(root.row)
}
standardButtons: Dialog.Ok | Dialog.Cancel
}

One way to prevent this is to check that the property is not undefined:
text: model.id === undefined ? "" : model.id

I'm not going to fix the code, but I am going to try to explain why you are having trouble. I feel the why of things will help more people.
This image may not be 100% accurate but it is how one must visualize things in their mind. You have three distinct lanes an object lives in when you introduce QML: C++, QML Engine, and JavaScript engine. Each and every one of those lanes believes beyond a shadow of a doubt that they control the life and death of the object.
When you are just passing integers around that are passed by value, this is no issue. When you are passing QStrings around, because of the copy-on-write charter of Qt, this is only a minor issue. When you are passing real objects around, worse yet, complex containers of real objects, you have to understand this completely. The answer that "fixed" your problem really only masked it. You will find there is a lot of QML and JavaScript code out there that exists only to mask an application not respecting the lanes.
Had this application used an actual database there would be a fourth lane. Yes, SQLite provides an SQL interface and allows many things, but an actual database has an external engine providing shared access and controlling the life of cursors. SQLite files tend to be single user. Yes, multiple threads within your application can access it, but while your application is running you cannot open a terminal window and use command line tools to examine the database. Think of it more as a really nice indexed file system without sharing.
So, you create an object in C++ and then expose it to QML. The QML engine now believes beyond a doubt that it controls the life and death of that object despite not having its own copy.
QML is really feeble. It can't actually do much, so it has to hand any significant object off to JavaScript. The JavaScript engine now believes beyond a shadow of a doubt that it now controls the life and death of that object.
You need to also envision these lanes as independent threads. There will most likely be many threads within each, but, in general, any signal or communication between these will go on the event loop of the target as a queued event. That means it will only be processed when it finally bubbles to the top of the queue for that event loop.
This, btw, is why you can never use Smart Pointers when also using QML/JavaScript. Especially the kind that do reference counting and delete the object when there are no more references. There is no way for the C++ lane to know that QML or JavaScript are still using the object.
The answer telling you to check for undefined property is masking the problem that your code is drunk driving across all lanes. Eventually, on a faster (or sometimes slower) processor garbage collection for one of the lanes will run at a most inopportune moment and you will be greeted with a stack dump. (The drunk driving code will hit a tree that does not yield.)
Correct Solution #1:
Never use QML or JavaScript. Just use C++ and Widgets. Stay entirely within the C++ lane. If that is a route open to you it's a good way to go. There is an awful lot of production code out there doing just that. You can obtain a copy of this book (or just download the source code from the page) and muddle through building it.
Correct Solution #2:
Never actually do anything in QML or JavaScript. This is an all together different solution than #1. You can use QML for UI only, leaving all logic in C++. Your code is failing because you are trying to actually do something. I haven't built or tried your code. I simply saw
function deleteRowFromDatabase(row)
which shouldn't exist at all. C++ holds your model. You emit a signal from your QML/JavaScript lanes when user action requires deletion. This signal becomes a queued event in the C++ lane. When it is processed the row will be deleted and the model updated. If you have properly exposed your model to QML it will emit some form of "model changed" signal and the UI will update accordingly. One of the main points of MVC (Model-View-Controler) is communication to/from the model. When the data changes it notifies the view(s).
Correct Solution #3:
Never use C++. Have your C++ be a "Hello World!" shell that just launches your QML. Never create and share an object between C++ and the other two lanes. Do everything inside of JavaScript and QML.
Binding loop errors, in general, happen when code drunk drives across all three lanes. They also happen when code doesn't view each lane as at least one distinct thread with its own event loop. The C++ lane hasn't finished (perhaps not even started) the delete operation but your code is already trying to use the result.
I don't know why, but some people edit these things and delete the correct answers. The full information was too long for SO and is contained here,
https://www.logikalsolutions.com/wordpress/uncategorized/so-you-cant-get-your-qt-models-to-work-with-qml/
with source even.

Related

uniquely identify a QQuickItem instance across app restart

Context:
We are developing an IDE for VR/AR effects editing. Users would like to have MACRO recording. Something similar to Selenim/AutoIT in spirit, but specific for this app with deep dataModel integration. Users are trained JS developers. Software GUI is Qt/QML (mostly qml)
Current Blocker
I need a way to uniquely identify a specific QQuickItem by its objectName:
across multiple restart of the app.
across platform (OS/Cpu/...)
name should be human readable enough for use in JS Macro
Should serialise enough information from QQuickItem/QEvent to post a valid event
It is acceptable to use CI static analysis to ensure all item have a valid unique name and detect name changes.
The problem here is some button, for instance the number buttons have exactly the same fqn/path/name unless I use and ugly hack, renaming it by the text of its sub-component:
Component.onCompleted: {
objectName = "button." + button.text
}
property bool keepObjectName: true
Here a fully qualified name based on metaObject()->className() is not enough, as it wont be unique. qml ids are not usable as per documentation.
Question: Is there a way in Qt to obtain such unique identifier?
Related Question:
Qt GUI event recording and playback
Abandoned Road:
print trace of signals/slots called
Reason: Most events in IDE do not use connect() the standard Qt way. Too Low level.
Draft Technical Solution / POC (mostly for reference)
https://doc.qt.io/qt-5/qtdoc-demos-calqlatr-example.html
Using the Qt QML calculator example here. Added this to main.cpp:
#include "Filter.h"
#include <unordered_map>
std::unordered_map<QString,QQuickItem*> map;
void install(QQuickItem* root, KeyPressEater* keyPressEater, const QString& fqn){
if(!root->property("keepObjectName").isValid() || !root->property("keepObjectName").value<bool>()){
qDebug("setObjectName: %s", root->metaObject()->className());
qDebug("Object original name:%s", root->objectName().toStdString().c_str());
root->setObjectName(root->metaObject()->className());
}
else{
qDebug("unchanged Object Name: %s", root->objectName().toStdString().c_str());
}
auto fqnRoot = fqn.isEmpty() ? root->objectName() : fqn + "." + root->objectName();
qDebug("Object fqn: %s", fqnRoot.toStdString().c_str());
root->installEventFilter(keyPressEater);
keyPressEater->insert(root,fqnRoot);
for(auto* child: root->childItems()){
QString fqn = fqnRoot + "." + child->metaObject()->className();
install(child, keyPressEater,fqnRoot);
}
qDebug("\n\n\n");
}
Filter.h looks like this:
#ifndef FILTER_H
#define FILTER_H
#include <QQuickItem>
#include <QtCore>
#include <unordered_map>
#include <QQuickItem>
class KeyPressEater : public QObject
{
Q_OBJECT
public:
void insert(QQuickItem* item,const QString& str){
if(map2.find(str) != map2.end())
{
qDebug("Duplicate object name:%s", str.toStdString().c_str());
}
else{
qDebug("Object name:%s", str.toStdString().c_str());
map.insert({item,str});
map2.insert({str,item});
}
}
void play(){
playing = true;
for(auto p: records){
//p.second->event(p.first);
QCoreApplication::postEvent(p.second, p.first);
QCoreApplication::sendPostedEvents();
}
playing = false;
}
protected:
bool eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress) {
//QMouseEvent *keyEvent = static_cast<QMouseEvent *>(event);
qDebug("click");
QQuickItem *item = static_cast<QQuickItem *>(obj);
qDebug("%s",map[item].toStdString().c_str());
qDebug("%s",item->metaObject()->className());
if(!playing){
records.push_back({event->clone(),item});
}
return false;
} else {
// standard event processing
if(event->type() == QEvent::KeyPress){
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if(keyEvent->key() == 32){
play();
}
}
return QObject::eventFilter(obj, event);
}
}
std::unordered_map<QQuickItem*,QString> map;
std::unordered_map<QString,QQuickItem*> map2;
std::atomic<bool> playing = false;
std::vector<std::pair<QEvent*,QObject*>> records;
};
#endif // FILTER_H
How to use:
Copy the above the main.cpp and new filter.h file in the calculator app example. Call install in main function:
install(view.rootObject(), &keyPressEater,"");

Adding/ Removing markers in quickwidget openstreet map

I'm using QQuickwidget in my QT5 gui. I've loaded an openstreet map on it by adding qml files accordingly.
By adding a function in the qml file, I call it through the cpp file by using QMetaObject::invokeMethod. This function adds markers at certain coordinates. This is because I want to control my markers through c++ code itself.
My problem: I am able to load the map and the markers successfully, but I'm not able to remove the markers. My aim is to show the path of a moving object on a map. Therefore, using a timer, I want to update it's position periodically. Every t_samp seconds, I want to remove the marker and add it somewhere else.
the 'item' created in the addMarker code is added to the map by using map.addMapItem(item). By appending map.removeMapItem(item) to the function, the marker disappears. But, the problem is, I can't seem to be able to access 'item' outside the function. Therefore, I cant use map.removeMapItem since I cant input the marker.
I also tried making the function output 'item', so that I can then use it to add/remove the marker. Unfortunately, I dont know the data type of item, and hence cant receive it.
mapview.qml:
import QtQuick 2.12
import QtLocation 5.12
import QtPositioning 5.12
Item {
id: window
Plugin
{
id: mapPlugin
name:"osm"
}
function addMarker(latitude, longitude)
{
var component= Qt.createComponent("qrc:///qml/marker.qml")
var item= component.createObject(window, {coordinate: QtPositioning.coordinate(latitude,longitude)})
map.addMapItem(item)
}
Map
{
id: map
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(15.4561,73.8021);
zoomLevel: 14
}
}
marker.qml:
import QtQuick 2.12
import QtLocation 5.12
import QtPositioning 5.12
MapQuickItem
{
id: marker
anchorPoint.x: marker.width / 4
anchorPoint.y: marker.height
sourceItem: Image
{
id: icon
source: "qrc:///images/mapmark.png"
sourceSize.width: 50
sourceSize.height: 50
}
}
mainwindow.cpp: (only relevant snippet)
QObject* target= qobject_cast<QObject*>(ui->quickWidget->rootObject());
QString functionName= "addMarker";
QMetaObject::invokeMethod(target,functionName.toUtf8().constData(), Qt::AutoConnection, Q_ARG(QVariant, 15.4561), Q_ARG(QVariant,73.8021));
Instead of exporting the QML marker to C++, it is best to export a QObject from C++ to QML, and since you want to handle several markers you must use a model.
Explanation of the approach:
The MVC pattern is Qt's natural way of handling a lot of information, and for this it implements views such as MapItemView, and models that can be created based on QAbstractXXXModel. So only the responsibility is to specialize the classes for the objective, such as implementing the logic of just keeping n elements and if there is a new element, remove the oldest one.
Why is it better to export a QObject to QML? The life cycle of the objects in QML are handled by QML, so in your case you could access the markers at a given time QML could delete it so that the pointer in C ++ would append non-reserved memory. Another advantage is that the Q_PROPERTY are recognized in QML and the data type is known by QML and C ++, unlike if you export a QML object to C ++ since only the properties of QObject or QQuickItem will be used. Also when exported using setContextProperty the QObject is global. The disadvantage is that more code is added. For more details read Interacting with QML from C++.
markermodel.h
#ifndef MARKERMODEL_H
#define MARKERMODEL_H
#include <QAbstractListModel>
#include <QGeoCoordinate>
class MarkerModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QGeoCoordinate current READ current NOTIFY currentChanged)
public:
enum MarkerRoles{
PositionRole = Qt::UserRole + 1000,
};
explicit MarkerModel(QObject *parent = nullptr);
void moveMarker(const QGeoCoordinate & coordinate);
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;
int maxMarkers() const;
void setMaxMarkers(int maxMarkers=0);
QGeoCoordinate current() const;
signals:
void currentChanged();
private:
void insert(int row, const QGeoCoordinate & coordinate);
void removeLastMarker();
QList<QGeoCoordinate> m_markers;
QGeoCoordinate m_current;
int m_maxMarkers;
};
#endif // MARKERMODEL_H
markermodel.cpp
#include "markermodel.h"
MarkerModel::MarkerModel(QObject *parent)
: QAbstractListModel(parent),
m_maxMarkers(0)
{
}
void MarkerModel::moveMarker(const QGeoCoordinate &coordinate)
{
QGeoCoordinate last = m_current;
m_current = coordinate;
Q_EMIT currentChanged();
if(!last.isValid())
return;
if(m_maxMarkers == 0){
insert(0, last);
return;
}
if(rowCount() >= m_maxMarkers){
while (rowCount() >= m_maxMarkers)
removeLastMarker();
removeLastMarker();
}
insert(0, last);
}
int MarkerModel::maxMarkers() const
{
return m_maxMarkers;
}
void MarkerModel::setMaxMarkers(int maxMarkers)
{
m_maxMarkers = maxMarkers > 1 ? maxMarkers: 0;
}
QGeoCoordinate MarkerModel::current() const
{
return m_current;
}
int MarkerModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_markers.count();
}
QVariant MarkerModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if(role == PositionRole)
return QVariant::fromValue(m_markers[index.row()]);
return QVariant();
}
QHash<int, QByteArray> MarkerModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[PositionRole] = "position";
return roles;
}
void MarkerModel::insert(int row, const QGeoCoordinate & coordinate)
{
beginInsertRows(QModelIndex(), row, row);
m_markers.insert(row, coordinate);
endInsertRows();
}
void MarkerModel::removeLastMarker()
{
if(m_markers.isEmpty())
return;
beginRemoveRows(QModelIndex(), rowCount()-1, rowCount()-1);
m_markers.removeLast();
endRemoveRows();
}
mainwindow.h
// ...
MarkerModel marker_model;
// ...
mainwindow.cpp
// ...
ui->quickWidget->rootContext()->setContextProperty("marker_model", &marker_model);
ui->quickWidget->setSource(QUrl("qrc:/mapview.qml"));
// ...
main.qml
// ...
Map{
id: map
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(15.4561,73.8021);
zoomLevel: 14
Marker{
coordinate: marker_model.current
}
MapItemView{
model: marker_model
delegate: Marker{
coordinate: model.position
}
}
}
// ...
The complete example is here

QTableView: endMoveRows in model resets horizontal header sizes

I'm trying to implement drag'n'drop reordering of rows in a QTableView.
The operation needs to actually reorder the underlying data, therefore reordering the vertical header rows doesn't seem like a good solution.
I instead opted for the underlying model to handle this by providing the row indices in its mimeData function and accepting this list in dropMimeData. In the dropMimeData function, I use the beginMoveRows and endMoveRows to move individual rows visually, in addition to moving the underlying data. This approach seems to work, with only one shortcoming: as soon as I call endMoveRows, the QTableView's horizontal header resets all its section sizes to defaults.
Am I missing something I need to do, or is this a bug in Qt (or even intended behavior)? Is there any other way to handle drag'n'drop reordering?
Here is a simplified piece of code that shows the same behavior:
class Model: public QAbstractTableModel
{
public:
Model():
m_Items({"A", "B", "C", "D", "E"})
{
}
virtual QVariant data(const QModelIndex & a_Parent, int a_Role) const override
{
return QString("%1 - %2").arg(m_Items[a_Parent.row()]).arg(a_Parent.column());
}
virtual int rowCount(const QModelIndex & a_Parent) const override
{
return m_Items.count();
}
virtual int columnCount(const QModelIndex & a_Parent) const override
{
return 4;
}
void moveNow()
{
// Moves the last row as the 3rd row:
auto count = m_Items.count();
beginMoveRows(QModelIndex(), count, count, QModelIndex(), 2);
m_Items.insert(2, m_Items.last());
m_Items.pop_back();
endMoveRows();
}
protected:
QStringList m_Items;
};
static Model g_Model;
MainWindow::MainWindow(QWidget * parent):
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// "ui" created by QtCreator, has a "tableView" and a "pushButton"
ui->setupUi(this);
ui->tableView->setModel(&g_Model);
ui->tableView->horizontalHeader()->resizeSection(0, 200);
ui->tableView->horizontalHeader()->resizeSection(1, 100);
ui->tableView->horizontalHeader()->resizeSection(2, 50);
ui->tableView->horizontalHeader()->resizeSection(3, 80);
connect(ui->pushButton, &QPushButton::clicked,
[this]()
{
// Outputs 200 on first click
qDebug() << ui->tableView->horizontalHeader()->sectionSize(0);
g_Model.moveNow();
// Outputs 100
qDebug() << ui->tableView->horizontalHeader()->sectionSize(0);
}
);
}
I found out that calling emit layoutAboutToBeChanged() just before the move operation fixes the issue:
void moveNow()
{
emit layoutAboutToBeChanged();
auto count = m_Items.count();
beginMoveRows(QModelIndex(), count, count, QModelIndex(), 2);
m_Items.insert(2, m_Items.last());
m_Items.pop_back();
endMoveRows();
}
This seems to contradict the documentation for beginMoveRows, which indicates that it is a replacement for calling this function. Also there must not be a matching emit layoutChanged() after endMoveRows, otherwise the columns are, again, reset.
This all together leads me to believe it's an actual bug in Qt.

C++/QML: ListView is not updated on dataChanged signal from QAbstractListModel

I am trying to write a QML Gui for a large dynamic C/Fortran simulation. The data I want to display is stored in Fortran Common blocks and updated on fixed time steps. My problem is that QML ListView does not refresh when the dataChanged signal is emitted after each time step, although the signal is received by the Gui (test is in the code below).
I am probably missing out something really obvious because when I flick my ListView down and up again, the displayed data is updated and correct (I guess because the QML engine re-renders elements when they get "out of sight" and back in again). So the only thing that does not work is that the ListView gets updated every time the dataChanged signal is received and not only when it is re-rendered. Below is a more detailed description of my approach and the relevant code parts.
Each simulation entity has several attributes (alive, position...), so I decided to create a ListModel containing a DataObject for each entity. This is the corresponding header file (the actual simulation data is declared as extern structs in "interface.h", so I can access it via pointer):
"acdata.h"
#include <QtCore>
#include <QObject>
#include <QtGui>
extern "C" {
#include "interface.h"
}
class AcDataObject : public QObject
{
Q_OBJECT
public:
explicit AcDataObject(int id_, int *pac_live, double *pac_pos_x, QObject *parent = 0) :
QObject(parent)
{
entity_id = id_;
ac_live = pac_live;
ac_pos_x = pac_pos_x;
}
int entity_id;
int *ac_live;
double *ac_pos_x;
};
class AcDataModel : public QAbstractListModel
{
Q_OBJECT
public:
enum RoleNames {
IdRole = Qt::UserRole,
LiveRole = Qt::UserRole + 1,
PosXRole = Qt::UserRole + 2
};
explicit AcDataModel(QObject *parent = 0);
virtual int rowCount(const QModelIndex &parent) const;
virtual QVariant data(const QModelIndex &index, int role) const;
Q_INVOKABLE Qt::ItemFlags flags(const QModelIndex &index) const Q_DECL_OVERRIDE;
void do_update();
protected:
virtual QHash<int, QByteArray> roleNames() const;
private:
QList<AcDataObject*> data_list;
QHash<int, QByteArray> m_roleNames;
QModelIndex start_index;
QModelIndex end_index;
signals:
void dataChanged(const QModelIndex &start_index, const QModelIndex &end_index);
};
Like the header, the .cpp file is also adapted from what you can find in the Qt5 Cadaques Book here, except that my constructor iterates over all simulation entities to set the pointers. Additionally, there is the do_update function that emits the dataChanged signal for the whole list.
"acdata.cpp"
#include "acdata.h"
AcDataModel::AcDataModel(QObject *parent) :
QAbstractListModel(parent)
{
m_roleNames[IdRole] = "entity_id";
m_roleNames[LiveRole] = "ac_live";
m_roleNames[PosXRole] = "ac_pos_x";
for (int i = 0; i < MAX_ENTITIES; i++) // MAX_ENTITIES is defined in interface.h
{
AcDataObject *data_object = new AcDataObject( i,
&fdata_ac_.ac_live[i], // fdata_ac_ is the C struct/Fortran common block defined in interface.h
&fdata_ac_.ac_pos_x[i] );
data_list.append(data_object);
}
}
int AcDataModel::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return data_list.count();
}
QVariant AcDataModel::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row < 0 || row >= data_list.count()) {
return QVariant();
}
const AcDataObject *data_object = data_list.at(row);
switch(role) {
case IdRole: return data_object->entity_id;
case LiveRole: return *(data_object->ac_live);
case PosXRole: return *(data_object->ac_pos_x);
}
return QVariant();
}
QHash<int, QByteArray> AcDataModel::roleNames() const
{
return m_roleNames;
}
void AcDataModel::do_update() {
start_index = createIndex(0, 0);
end_index = createIndex((data_list.count() - 1), 0);
dataChanged(start_index, end_index);
}
Qt::ItemFlags AcDataModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {return 0;}
return Qt::ItemIsEditable | QAbstractItemModel::flags(index);
}
When the simulation is running, do_update() is called every second. I have created a test Gui with a ListView and exposed my model to it with:
Excerpt from "threadcontrol.cpp"
acdata = new AcDataModel();
viewer = new QtQuick2ApplicationViewer();
viewer->rootContext()->setContextProperty("acdata", acdata);
viewer->setMainQmlFile(QStringLiteral("../lib/qml_gui/main.qml"));
viewer->showExpanded();
(This code is part of a larger file that controls the different threads. I am quite sure the rest is not relevant to the actual problem and this question is getting really long...)
So finally there is main.qml. It contains a list with MAX_ENTITIES elements and each elements holds text fields to display my data. I have also added a Connections element to check if the dataChanged signal is received by the Gui.
"main.qml"
ListView {
id: listviewer
model: acdata
delegate: Rectangle {
/* ... some formatting stuff like height etc ... */
Row {
anchors.fill: parent
Text {
/* ... formatting stuff ... */
text: model.entity_id
}
Text {
/* ... formatting stuff ... */
text: model.ac_live
}
Text {
/* ... formatting stuff ... */
text: model.ac_pos_x
}
}
}
Connections {
target: listviewer.model // EDIT: I drew the wrong conclusions here, see text below!
onDataChanged: {
console.log("DataChanged received")
}
}
}
When running the simulation, the "DataChanged received" message is printed every second.
Edit: I was connecting to the ListModel and not to the ListView here, although the ListView has to receive the dataChanged signal. As the console log does not work when connecting to listviewer, I am probably missing the connection between listView and dataChanged signal. However, I think this should work automatically when implementing the dataChanged signal?
Additional information: I have found a similar problem here with Qt Map and it actually seemed to be a bug that was fixed in Qt 5.6. However, running qmake with Qt 5.7 did not fix my problem.
You mustn't declare the dataChanged() signal in your class, because you want to emit the signal AbstractItemModel::dataChanged(). If you re-declare it you add a comleptely new and different Signal that is not connected anywhere. If you remove the declaration in acdata.h everything should work fine.

Threaded renderer in QML

Threaded renderer is not working in the following code. I'm using Qt 5.4 on Arch linux-3.14 with proprietary drives.
---------- mytext.h -----------
#include <QObject>
class Thing : public QObject {
Q_OBJECT
Q_PROPERTY(int qm_no READ qm_no NOTIFY qm_noChanged)
public:
Q_INVOKABLE void loop();
int qm_no();
signals:
void qm_noChanged();
private:
int m_no;
};
---------- mytext.cpp ----------
#include "mytext.h"
#include <unistd.h>
int Thing::qm_no() {
return m_no;
}
void Thing::loop() {
while(true) {
m_no += 1;
emit qm_noChanged();
usleep(1000000);
}
}
--------- main.cpp -----------
#include <QQmlContext>
#include <QQuickView>
#include <QGuiApplication>
#include <QtQml>
#include "mytext.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Thing myTh;
QQuickView view;
view.rootContext()->setContextProperty("qmyTh",&myTh);
view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();
return app.exec();
}
------- main.qml ----------
import QtQuick 2.0;
Rectangle {
id: root
width: 200
height: 200
property var name: "test"
Text {
anchors.fill: parent
text: name
}
MouseArea {
anchors.fill: parent
onClicked: {
qmyTh.loop()
}
}
Connections {
target:qmyTh
onQm_noChanged: {
name = qmyTh.qm_no;
}
}
}
Explanation::
There is a classes Thing , with its object myTh. The function of class Thing is to provide an invokable function which here is loop. This function will then continuously update the m_no value and emit signal. Now the question is that how can I update the Text (name property) while the infinite loop is running which keeps on updating the value to be displayed ?
The code is correct for what concerns the QML part (now) and it works correctly. What is not correct is the C++ implementation. if you remove the while loop, leaving its content, and execute your code you'll see that the text is correctly updated.
The reason of such behaviour should be researched in the Qt quick render implementation. On certain platforms the render is not threaded by default. I guess you are working on Windows (see "Qt Quick" here). Hence, in a not threaded setting, by updating the variable and then sleeping, you are blocking the whole application, preventing the gui update.
You can use a QTimer to schedule the method execution at intervals, or set up a QML Timer for the exact same purpose.
Also, you don't need to save the new value in a temp variable (especially a var one which adds useless checks in this case). By setting an id inside the Text element you can directly set the text property. Here the revisited code:
import QtQuick 2.0;
Rectangle {
id: root
width: 200
height: 200
Text {
id: myText // the id!
anchors.fill: parent
text: "dummy" // dummy text || left empty || use "qmyTh.qm_no" (ensure a correct value is returned at creation time)
}
MouseArea {
anchors.fill: parent
onClicked: {
qmyTh.loop()
}
}
Connections {
target:qmyTh
onQm_noChanged: myText.text = qmyTh.qm_no // text directly set!
}
}
EDIT
It seems like the used render is threaded, hence my reasoning does not apply. There should be other problems. You can try to track down the problem exploiting the debugger and by adding console.info(...) statements in the JS handlers. Searching for the problem could be useful to track (possible) bugs in the libraries.
Depending on the background processing you have to run, I still think that using timers wouldn't be that bad. It really, truly depends on what you want to achieve. However, if you want to try threads, Qt documentation is full of explanations (as usual).
Have a look at this, this
and also absolutely this. Mind that a "moved" object (see the links) cannot be registered as a context property so you have to use one of the other ways to work with threads in a QML project.