Dynamic translation of combobox qml - qt

I've added translation to my qt/qml app using this tutorial
https://retifrav.github.io/blog/2017/01/04/translating-qml-app/
https://github.com/retifrav/translating-qml
And most seems to work well except that the values of the combobox dont get update with dynamic translate.
Im using qt 5.11.2.
By a combobox i mean this:
ComboBox {
textRole: "text"
Layout.fillWidth: true
model: ListModel {
Component.onCompleted: {
append({text: qsTr("None")})
append({text: qsTr("Subpanel")})
append({text: qsTr("All")})
}
}
}
ComboBox {
textRole: "text"
Layout.fillWidth: true
model: ListModel {
ListElement{text: qsTr("None")}
ListElement{text: qsTr("Subpanel")}
ListElement{text: qsTr("All")}
}
}
None of them gets updated.
I've done some research and found this on bug reports
https://bugreports.qt.io/browse/QTBUG-68350
This seems to get fixed on 5.12, but for various reason we need to keep the same version, is there a way i can fix it for this version? (5.11.2)
EDIT: I dont find a way to translate comboBox. Is there another way of doing translations? even if it means to open a new instance of the app? Can someone point me to a link? Can't find a way to do this.
EDIT2: Is there a way to force the model of the combobox to be updated by javascript? when the changeLanguage() method is called?
note: As a complaint i'm finding the support / community to get answers for Qt problems terrible, really bad, but maybe its my problem.

One option is to add a QAbstracstListModel which does the translation. I made myself a base class, which can be inherited. This also gives you a lot of flexibility for converting a selected item to a value (in this example I am using int, but you can make it anything), which is connected to a C++ backend (I used backend.selectedPanel for your example)
<< Edit: See answer of Felix for nice addition of dynamic translation >>
base header:
class baseEnum : public QAbstractListModel
{
Q_OBJECT
public:
virtual int rowCount(const QModelIndex &parent) const = 0;
virtual QVariant data(const QModelIndex &index, int role) const = 0;
QHash<int, QByteArray> roleNames() const;
Q_INVOKABLE int getIndex(int value);
Q_INVOKABLE int getValue(int index);
}
base cpp:
QHash<int, QByteArray> baseEnum::roleNames() const
{
QHash<int, QByteArray> result;
result.insert(Qt::DisplayRole, "text");
result.insert(Qt::UserRole + 1, "value");
return result;
}
int baseEnum::getIndex(int value)
{
for(int i=0;i<rowCount(QModelIndex());++i)
if(data(createIndex(i, 0, nullptr), Qt::UserRole + 1).toInt() == value)
return i;
return -1;
}
int baseEnum::getValue(int index)
{
return data(createIndex(index, 0, nullptr), Qt::UserRole + 1).toInt();
}
derived header:
class FancyEnum : public baseEnum
{
Q_OBJECT
public:
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
};
derived cpp:
int FancyEnum::rowCount(const QModelIndex &parent) const
{
if(!parent.isValid())
return 5;
return 0;
}
QVariant FancyEnum::data(const QModelIndex &index, int role) const
{
switch(index.row())
{
case 0: return role == Qt::DisplayRole ? QVariant(tr("None")) : QVariant(0);
case 1: return role == Qt::DisplayRole ? QVariant(tr("Subpanel")) : QVariant(1);
case 2: return role == Qt::DisplayRole ? QVariant(tr("All")) : QVariant(2);
}
return role == Qt::DisplayRole ? QVariant(QString("<%1>").arg(index.row())) : QVariant(0);
}
Register it somewhere:
qmlRegisterType<FancyEnum>("your.path.here", 1, 0, "FancyEnum");
usage in QML:
ComboBox {
model: FancyEnum { id: myEnum }
textRole: "text"
currentIndex: myEnum.getIndex(backend.selectedPanel) : 0
onActivated: backend.selectedPanel = myEnum.getValue(index) }
}

This is an addition to #Amfasis answer. It extends the very useful "baseEnum" model by adding the capability to detect and react to restranslation events
For the GUI to actually detect that the text was changed after a restranslation, the model must "notify" the gui that data has changed. However, to do that, the model must know when data changed. Thankfully, Qt has the LanguageChange event to do so. The following code catches that event and uses it to notify the gui of the data change.
// in the header file:
class baseEnum : public QAbstractListModel
{
Q_OBJECT
public:
// ... all the stuff from before
bool event(QEvent *event);
};
// and in the cpp file:
bool baseEnum::event(QEvent *ev)
{
if(ev) {
switch(ev->type()) {
case QEvent::LanguageChange:
// notifiy models that the display data has changed for all rows
emit dataChanged(index(0),
index(rowCount(QModelIndex{}) - 1),
{Qt::DisplayRole});
break;
}
}
return QAbstractListModel::event(ev);
}

Unfortunately, I can't test all the cases at the moment (and I don't have an access to the Qt 5.11.2), but I think this should work:
ComboBox {
textRole: "text"
Layout.fillWidth: true
displayText: qsTr(currentText)
model: ListModel {
ListElement{text: "None"}
ListElement{text: "Subpanel"}
ListElement{text: "All"}
}
delegate: Button {
width: ListView.view.width
text: qsTr(model.text)
}
}
Or, another way is to re-create a model when language is changed:
ComboBox {
id: combobox
textRole: "text"
Layout.fillWidth: true
model: ListModel {
dynamicRoles: true
}
Component.onCompleted: {
reload()
}
Connections {
target: trans // this is a translator from a git project you are referring to
onLanguageChanged: {
combobox.reload()
}
}
function reload() {
var i = combobox.currentIndex
combobox.model = [
{text: qsTr("None")},
{text: qsTr("Subpanel")},
{text: qsTr("All")}
]
combobox.currentIndex = i
}
}

Related

How to add an extra item to a QML ComboBox which is not in the model?

I have a QML ComboBox which has a QAbstractListModel attached to it. Something like this:
ComboBox {
model: customListModel
}
And I would like it to display an extra item in the drop down list which is not in the model.
For example, let's say there are two items in the customListModel: Apple and Orange.
And in the drop down list it should display the following options:
Select all
Apple
Orange
I can't add it to the model because it contains custom objects and I use this model a couple of other places in the program and it would screw up everything.
How can I add this "Select all" option to the ComboBox???
One way to do it is to create a proxy model of some sort. Here's a couple ideas:
You could derive your own QAbstractProxyModel that adds the "Select All" item to the data. This is probably the more complex option, but also the more efficient. An example of creating a proxy this way can be found here.
You could also make your proxy in QML. It would look something like this:
Combobox {
model: ListModel {
id: proxyModel
ListElement { modelData: "Select All" }
Component.onCompleted: {
for (var i = 0; i < customListModel.count; i++) {
proxyModel.append(customModel.get(i);
}
}
}
}
A solution is to customize the popup to add a header.
You could implement the entire popup component, or exploit the fact that its contentItem is a ListView and use the header property:
ListModel {
id: fruitModel
ListElement {
name: "Apple"
}
ListElement {
name: "Orange"
}
}
ComboBox {
id: comboBox
model: fruitModel
textRole: "name"
Binding {
target: comboBox.popup.contentItem
property: "header"
value: Component {
ItemDelegate {
text: "SELECT ALL"
width: ListView.view.width
onClicked: doSomething()
}
}
}
}
I found myself wanting to do something similar recently and was surprised that there's no simple way to do it; there are ways to do it but not really a dedicated API for it, not even for widgets.
I've tried both of the answers mentioned here and would like to summarise them, as well provide complete examples for each approach. My requirement was to have a "None" entry, so my answer is in that context, but you can easily replace that with "Select All".
Using QSortFilterProxyModel
The C++ code for this is based on this answer by #SvenA (thank you for sharing working code!).
Pros:
To avoid repeating myself too much: the pros for this are the absence of the cons in the other approach. For example: key navigation works, no need to touch any styling stuff, etc. These two alone are pretty big reasons why you would want to choose this approach, even if it does mean extra work writing (or copy-pasting :)) the model code (which is something you will only have to do once).
Cons:
Since you are using the 0 index for the "None" entry, you have to treat it as a special entry, unlike the -1 index, which is already established as meaning no item is selected. This means a little extra JavaScript code to handle that index being selected, but the header approach also requires this when it's clicked.
It is a lot of code for one extra entry, but again; you should only have to do it once, and then you can reuse it.
It is an extra level of indirection in terms of model operations. Assuming most ComboBox models are relatively small, this is not a problem. In practice I doubt this would be a bottleneck.
Conceptually a "None" entry could be considered a kind of metadata; i.e. it doesn't belong in the model itself, so this solution could be seen as less conceptually correct.
main.qml:
import QtQuick 2.15
import QtQuick.Controls 2.15
import App 1.0
ApplicationWindow {
width: 640
height: 480
visible: true
title: "\"None\" entry (proxy) currentIndex=" + comboBox.currentIndex + " highlightedIndex=" + comboBox.highlightedIndex
ComboBox {
id: comboBox
textRole: "display"
model: ProxyModelNoneEntry {
sourceModel: MyModel {}
}
}
}
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QSortFilterProxyModel>
#include <QDebug>
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit MyModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
private:
QVector<QString> mData;
};
MyModel::MyModel(QObject *parent) :
QAbstractListModel(parent)
{
for (int i = 0; i < 10; ++i)
mData.append(QString::fromLatin1("Item %1").arg(i + 1));
}
int MyModel::rowCount(const QModelIndex &) const
{
return mData.size();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!checkIndex(index, CheckIndexOption::IndexIsValid))
return QVariant();
switch (role) {
case Qt::DisplayRole:
return mData.at(index.row());
}
return QVariant();
}
class ProxyModelNoneEntry : public QSortFilterProxyModel
{
Q_OBJECT
public:
ProxyModelNoneEntry(QString entryText = tr("(None)"), QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override;
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &child) const override;
private:
QString mEntryText;
};
ProxyModelNoneEntry::ProxyModelNoneEntry(QString entryText, QObject *parent) :
QSortFilterProxyModel(parent)
{
mEntryText = entryText;
}
int ProxyModelNoneEntry::rowCount(const QModelIndex &/*parent*/) const
{
return QSortFilterProxyModel::rowCount() + 1;
}
QModelIndex ProxyModelNoneEntry::mapFromSource(const QModelIndex &sourceIndex) const
{
if (!sourceIndex.isValid())
return QModelIndex();
else if (sourceIndex.parent().isValid())
return QModelIndex();
return createIndex(sourceIndex.row()+1, sourceIndex.column());
}
QModelIndex ProxyModelNoneEntry::mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid())
return QModelIndex();
else if (proxyIndex.row() == 0)
return QModelIndex();
return sourceModel()->index(proxyIndex.row() - 1, proxyIndex.column());
}
QVariant ProxyModelNoneEntry::data(const QModelIndex &index, int role) const
{
if (!checkIndex(index, CheckIndexOption::IndexIsValid))
return QVariant();
if (index.row() == 0) {
if (role == Qt::DisplayRole)
return mEntryText;
else
return QVariant();
}
return QSortFilterProxyModel::data(createIndex(index.row(),index.column()), role);
}
Qt::ItemFlags ProxyModelNoneEntry::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
if (index.row() == 0)
return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
return QSortFilterProxyModel::flags(createIndex(index.row(),index.column()));
}
QModelIndex ProxyModelNoneEntry::index(int row, int column, const QModelIndex &/*parent*/) const
{
if (row > rowCount())
return QModelIndex();
return createIndex(row, column);
}
QModelIndex ProxyModelNoneEntry::parent(const QModelIndex &/*child*/) const
{
return QModelIndex();
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<ProxyModelNoneEntry>("App", 1, 0, "ProxyModelNoneEntry");
qmlRegisterType<MyModel>("App", 1, 0, "MyModel");
qmlRegisterAnonymousType<QAbstractItemModel>("App", 1);
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();
}
#include "main.moc"
Using ListView's header
Pros:
The -1 index -- which is already established as meaning no item is selected -- can be used to refer to the "None" entry.
No need to set up a QSortFilterProxyModel-subclass in C++ and expose it to QML.
Conceptually a "None" entry could be considered a kind of metadata; i.e. it doesn't belong in the model itself, so this solution could be seen as more conceptually correct.
Cons:
Not possible to select the "None" entry with arrow key navigation. I briefly tried working around this (see commented-out code), but had no success.
Have to mimic the "current item" styling that the delegate component has. What that entails depends on the style; if you wrote the style yourself, then you could move the delegate component into its own file and reuse it for the header. However, if you you're using someone else's style, you can't do that, and will have to write it from scratch (though, you will usually only need to do this once). For example, for the Default ("Basic", in Qt 6) style it means:
Setting an appropriate font.weight.
Setting highlighted.
Setting hoverEnabled.
Have to set displayText yourself.
Since the header item isn't considered a ComboBox item, the highlightedIndex property (which is read-only) will not account for it. Can be worked around by setting highlighted to hovered in the delegate.
Have to do the following when the header is clicked:
Set currentIndex (i.e. to -1 on click).
Close the ComboBox's popup.
Emit activated() manually.
main.qml:
import QtQuick 2.0
import QtQuick.Controls 2.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: "\"None\" entry (header) currentIndex=" + comboBox.currentIndex + " highlightedIndex=" + comboBox.highlightedIndex
Binding {
target: comboBox.popup.contentItem
property: "header"
value: Component {
ItemDelegate {
text: qsTr("None")
font.weight: comboBox.currentIndex === -1 ? Font.DemiBold : Font.Normal
palette.text: comboBox.palette.text
palette.highlightedText: comboBox.palette.highlightedText
highlighted: hovered
hoverEnabled: comboBox.hoverEnabled
width: ListView.view.width
onClicked: {
comboBox.currentIndex = -1
comboBox.popup.close()
comboBox.activated(-1)
}
}
}
}
ComboBox {
id: comboBox
model: 10
displayText: currentIndex === -1 ? qsTr("None") : currentText
onActivated: print("activated", index)
// Connections {
// target: comboBox.popup.contentItem.Keys
// function onUpPressed(event) { comboBox.currentIndex = comboBox.currentIndex === 0 ? -1 : comboBox.currentIndex - 1 }
// }
}
}
Conclusion
I agree with the idea that "None" and "Select All" are more metadata than model data. In that sense I prefer the header approach. In my particular use case that made me look into this, I don't allow key navigation and I have already overridden the delegate property of ComboBox, so I can reuse that code for the header.
However, if you need key navigation, or you don't want to have to reimplement the delegate for the header, the QSortFilterProxyModel approach would be more practical.

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"
}
}
}
// ...

QML ListView is not updated on model reset

Qt 5.8, Windows 10.
Quick Controls 2 application. In QML I have a ListView with a model derived from QAbstractListModel.
In the model I have the following code:
void MediaPlaylistModel::update()
{
beginResetModel();
{
std::unique_lock<std::mutex> lock(m_mutex);
m_ids = m_playlist->itemsIds();
}
endResetModel();
}
Nothing happens in QML view after calling this method: list is not updated.
If I go back and then forward (to the page with the ListView) - it'll contain updated data. Model object instance is the same always.
Am I doing something wrong?
Update #1:
The only methods I override are:
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex &index, int role) const override;
Update #2:
C++ model code:
MediaPlaylistModel::MediaPlaylistModel(
QSharedPointer<AbstractMediaPlaylist> playlist,
QObject *parent) :
base_t(parent),
m_playlist(playlist)
{
Q_ASSERT(m_playlist);
connect(playlist.data(), &AbstractMediaPlaylist::changed,
this, &MediaPlaylistModel::update);
update();
}
QHash<int, QByteArray> MediaPlaylistModel::roleNames() const
{
QHash<int, QByteArray> result;
result[IdRole] = "id";
result[TitleRole] = "title";
result[DurationRole] = "duration";
return result;
}
void MediaPlaylistModel::update()
{
Q_ASSERT_SAME_THREAD;
beginResetModel();
{
std::unique_lock<std::mutex> lock(m_mutex);
m_ids = m_playlist->itemsIds();
}
endResetModel();
}
int MediaPlaylistModel::rowCount(
const QModelIndex &parent) const
{
Q_UNUSED(parent);
std::unique_lock<std::mutex> lock(m_mutex);
return static_cast<int>(m_ids.size());
}
QVariant MediaPlaylistModel::data(
const QModelIndex &index,
int role) const
{
auto row = static_cast<size_t>(index.row());
int id = 0;
{
std::unique_lock<std::mutex> lock(m_mutex);
if (row >= m_ids.size())
return QVariant();
id = m_ids[row];
}
if (role == IdRole)
return id;
QVariant result;
auto item = m_playlist->item(id);
switch(role)
{
case Qt::DisplayRole:
case TitleRole:
result = item.title;
break;
case DurationRole:
result = item.duration;
break;
}
return result;
}
QML code:
import QtQuick 2.7
import QtQuick.Controls 2.0
import com.company.application 1.0
Page
{
id : root
property int playlistId
property var playlistApi: App.playlists.playlist(playlistId)
ListView
{
id : playlist
anchors.fill: parent
model: playlistApi.model
delegate: ItemDelegate
{
text: model.title
width: parent.width
onClicked: App.player.play(playlistId, model.id)
}
ScrollIndicator.vertical: ScrollIndicator {}
}
}
Update #3:
When the model is updated (one item added), something strange happens with QML ListView: in addition to fact that it's not updated (and it does not call
MediaPlaylistModel::data to retrieve new items), existing items got damaged. When I click on existed item, it's model.id property is always 0. E.g. at app start its model.id was 24, after one item added its model.id became 0.
Update #4:
App.playlists.playlist(playlistId) returns pointer to this class instance:
class CppQmlPlaylistApi :
public QObject
{
Q_OBJECT
Q_PROPERTY(QObject* model READ model NOTIFY modelChanged)
Q_PROPERTY(QString title READ title WRITE setTitle NOTIFY titleChanged)
public:
explicit CppQmlPlaylistApi(
int playlistId,
QWeakPointer<CorePlaylistsManager> playlistsMgr,
QObject *parent = 0);
QObject* model() const;
QString title() const;
void setTitle(const QString &title);
signals:
void modelChanged();
void titleChanged();
void loadPlaylistRequested(int id);
protected slots:
void onPlaylistLoaded(int id);
void onPlaylistRemoved(int id);
protected:
int m_playlistId = 0;
QWeakPointer<CorePlaylistsManager> m_playlistsMgr;
QSharedPointer<QAbstractItemModel> m_model;
};
The model was in non-GUI thread.
I was getting these debug messages (thanks to AlexanderVX for pointing me out):
QObject::connect: Cannot queue arguments of type 'QQmlChangeSet'
(Make sure 'QQmlChangeSet' is registered using qRegisterMetaType().)
Moving the model object to GUI thread fixed the problem.
Your code, as provided, is good. On the QML side, as long as your model is bound, and not dynamically re-created in JS, you should be good too.
ListView {
model: mediaPlaylistModel
}
Problems can arise if you overloaded beginResetModel or endResetModel by accident. For tests purposes, you can try to emit the QAbstractItemModel::modelReset() signal, and see if it changes anything.
It's quite easy to miss something with QAbstractItemModel, resulting in nothing working anymore !

returning a custom QObject subclass from QAbstractListModel and using it in a ListView

How can I return a custom QObject sub-class from QAbstractListModel and use it in a QML ListView.
I tried to return the objects as display role and I use in my qml display.property to access properties, it works fine but I saw on some posts people using model as the qobject from qml and accessing properties as model.property. Am I missing something?.
Another question: If I want to expose the object at the ListView level and using it to set some other panel like a master-view detail is exposing the role (in my case display) as a variant property in the delegate and setting it at the listview level with the onCurrentItemChanged signal is the correct way to do it ??
this is what I am trying but it does not work:
#ifndef NOTE_H
#define NOTE_H
#include <QObject>
class Note : public QObject
{
Q_OBJECT
Q_PROPERTY(QString note READ note WRITE setNote NOTIFY noteChanged)
Q_PROPERTY(int id READ id WRITE setId NOTIFY idChanged)
QString m_note;
int m_id;
public:
explicit Note(QObject *parent = 0);
Note(QString note, int id, QObject *parent = 0);
QString note() const
{
return m_note;
}
int id() const
{
return m_id;
}
signals:
void noteChanged(QString note);
void idChanged(int id);
public slots:
void setNote(QString note)
{
if (m_note == note)
return;
m_note = note;
emit noteChanged(note);
}
void setId(int id)
{
if (m_id == id)
return;
m_id = id;
emit idChanged(id);
}
};
#endif // NOTE_H
the view model:
#ifndef NOTESVIEWMODEL_H
#define NOTESVIEWMODEL_H
#include <QAbstractListModel>
#include <QVector>
#include "note.h"
class NotesViewModel : public QAbstractListModel
{
Q_OBJECT
QVector<Note*> notes;
public:
NotesViewModel();
QVariant data(const QModelIndex &index, int role) const override;
int rowCount(const QModelIndex &parent) const override;
};
#endif // NOTESVIEWMODEL_H
implementation of the view model:
NotesViewModel::NotesViewModel()
{
notes.append(new Note("note 1", 1));
notes.append(new Note("note 2", 2));
notes.append(new Note("note 3", 3));
notes.append(new Note("note 4", 4));
notes.append(new Note("note 5", 5));
}
QVariant NotesViewModel::data(const QModelIndex &index, int role) const
{
qDebug() << "fetching data : " << index.row();
if(!index.isValid()) return QVariant();
if(index.row() >= 5) return QVariant();
if(role == Qt::DisplayRole)
return QVariant::fromValue(notes[index.row()]);
return QVariant();
}
int NotesViewModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return notes.count();
}
Since you've already answered your second question, let me take on the first one, i.e. display.propertyName vs model.propertyName
Basically the first one is just a short hand for model.display.propertyName, i.e. the "display" property of the model's data at the given index is being accessed. In your case that returns an object, which has properties on its on.
The model.propertyName could also be written as just propertyName, meaning the model's data() method is called with "role" being the numerical equivalent for "propertyName".
This mapping from "propertyName" to its numerical equivalent is done with the QAbstractItemModel::roleNames() method.
Its default implementation has some base mappings such as mapping "display" to Qt::DisplayRole.
I played a little with the qml ListView trying to figure out how to expose the currentItem data to the outside world. This is how I managed to do it, maybe it will be of use for newbies like me.
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListModel {
id: modell
ListElement {
fname: "houssem"
age: 26
}
ListElement {
fname: "Anna"
age: 26
}
ListElement {
fname: "Nicole"
age: 26
}
ListElement {
fname: "Adam"
age: 27
}
}
ListView {
id: lv
height: 100
width: 200
clip: true
model: modell
property string selectedName: currentItem.name
delegate: Component {
Item {
id: mainItem
width: ListView.view.width
height: 80
property string name: fname
Text {
text: "name " + fname + " age " + age
}
MouseArea {
anchors.fill: parent
onClicked: mainItem.ListView.view.currentIndex = index
}
}
}
}
Text {
anchors.right: parent.right
text: lv.selectedName
}
}
As you can see in the code, to expose the data of currentItem I had just to declare properties in the delegate Item (name property of type string in the present example) and then bind a property on ListView (selectedName in this example) to the currentItem.property, this way the property on the ListView will be updated automatically when I select other items from the list and I will have access to this items form other Items of the UI.

Exposing c++ model in qml

I have created this c++ class and exposed to a Qml ListView however, it has some problems. I can view that there are items in the list, however I am not able to see any data (I see 25 empty buttons). In the console, the following message is displayed: "type is undefined". I have checked and type should correctly a full string;
ListView{
id: listView
anchors.fill: parent
model: postsModel
delegate: Component{
Button{
text: type
}
}
}
#include "listmodel.h"
ListModel::ListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
QString ListItem::type() const
{
return m_type;
}
QVariantMap ListItem::dataMap() const
{
return m_dataMap;
}
void ListModel::addElement(const ListItem& element)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_elementsList << element;
endInsertRows();
}
QVariant ListModel::data(const QModelIndex & index, int role) const
{
if (index.row() < 0 || index.row() >= m_elementsList.count())
return QVariant();
const ListItem &item= m_elementsList[index.row()];
if (role == TypeRole)
return item.type();
else if (role == DataRole)
return item.dataMap();
return QVariant();
}
int ListModel::rowCount(const QModelIndex & parent) const {
return m_elementsList.count();
}
QHash<int, QByteArray> ListModel::roleNames()
{
QHash<int, QByteArray> roles;
roles[TypeRole] = "type";
roles[DataRole] = "dataMap";
return roles;
}
Alright, I found the solution to my problem. The problem was that the ListView was not being updated by the model that I implemented. This was due to my mistake consisting in not calling beginInsertRows() and endInsertRows() functions.

Resources