How to use C++ struct array for QML ComboBox? - c++

I've got a struct with two fields, for example:
struct testStruct
{
Q_GADGET
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
There is a QList<testStruct> m_testStructs member of my "AppEngine" class exposed to QML via
Q_PROPERTY(QList<testStruct> testStructs READ testStructs NOTIFY testStructsChanged).
It is filled like that:
testStruct newStruct1, newStruct2;
newStruct1.m_text = "text1";
newStruct1.m_value = "value1";
newStruct2.m_text = "text2";
newStruct2.m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
So I want to see "text" members in ComboBox list and use "value" members in further operations.
In fact QML ComboBox popup shows me the list of objects names when I set ComboBox's "textRole" property to "text" and "valueRole" to "value", but it does nothing for "currentText" or "currentValue" properties when I click the item, only "currentIndex" changes. Also "displayText" remains blank.
This is what I get in console when clicking those items:
qml: currentIndex: 0; currentText: ; currentValue: undefined
qml: currentIndex: 1; currentText: ; currentValue: undefined
So I see that ComboBox gets members of struct, but doesn't want to work with them. What should I do to make "currentText" and "currentValue" members of ComboBox work as they should?
Here are all the needed files:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "appengine.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(u"qrc:/qml_testComboBoxStruct/main.qml"_qs);
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
//exposing AppEngine class to QML
AppEngine appEngineObj;
QQmlContext *context = engine.rootContext();
context->setContextProperty("AppEngine", &appEngineObj);
engine.load(url);
return app.exec();
}
my custom class header AppEngine.h
#ifndef APPENGINE_H
#define APPENGINE_H
#include <QObject>
#include <QDebug>
struct testStruct
{
Q_GADGET
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
Q_DECLARE_METATYPE(testStruct)
class AppEngine : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<testStruct> testStructs READ testStructs NOTIFY testStructsChanged);
public:
explicit AppEngine(QObject *parent = nullptr);
QList<testStruct> testStructs();
private:
QList<testStruct> m_testStructs;
signals:
void testStructsChanged();
};
#endif // APPENGINE_H
my custom class cpp file AppEngine.cpp
#include "appengine.h"
AppEngine::AppEngine(QObject *parent)
: QObject{parent}
{
testStruct newStruct1, newStruct2;
newStruct1.m_text = "text1";
newStruct1.m_value = "value1";
newStruct2.m_text = "text2";
newStruct2.m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
qDebug() << "m_testStructs.length():" << m_testStructs.length();
}
QList<testStruct> AppEngine::testStructs()
{
qDebug() << "testStructs()";
return m_testStructs;
}
main.qml
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("C++ struct to QML ComboBox")
ComboBox
{
anchors.centerIn: parent
width: 180
height: 30
id: comboBoxID
textRole: "text"
valueRole: "value"
model: AppEngine.testStructs
onActivated:
{
console.log('currentIndex:', currentIndex, '; currentText:', currentText, ';currentValue:', currentValue);
}
}
}

As I checked in the main.qml model property cant find and understand as you show it is undefined.
qml: currentIndex: 0; currentText: ; currentValue: undefined
qml: currentIndex: 1; currentText: ; currentValue: undefined
from ListView::model property
The model provides the set of data that is used to create the items in
the view. Models can be created directly in QML using ListModel,
ObjectModel, or provided by C++ model classes. If a C++ model class is
used, it must be a subclass of QAbstractItemModel or a simple list.
For example, you can have this :
import QtQuick
import QtQuick.Controls
Window {
width: 640
height: 480
visible: true
title: qsTr("C++ struct to QML ComboBox")
ComboBox
{
id: comboBoxID
anchors.centerIn: parent
width: 180
height: 30
textRole: "text"
valueRole: "value"
model: ListModel {
id : model
ListElement { text: "text1" ; value : "value1" }
ListElement { text: "text2" ; value : "value2" }
ListElement { text: "text3" ; value : "value3" }
ListElement { text: "text4" ; value : "value4" }
}
onActivated:
{
console.log('currentIndex:', currentIndex, '; currentText:', currentText, '; currentValue:', currentValue);
}
}
}
Because you use QML ListModel if you want to define your model from C++ it must be a subclass of QAbstractItemModel or a simple list.
updated :
you need to use QStandardItemModel which inherits from QAbstractItemModel you cant inherit from the abstract interface because of that I use QStandardItemModel
in appengine.h:
#ifndef APPENGINE_H
#define APPENGINE_H
#include <QObject>
#include <QDebug>
#include <QStandardItemModel>
struct testStruct: public QStandardItemModel
{
Q_OBJECT
Q_PROPERTY(QString text MEMBER m_text);
Q_PROPERTY(QString value MEMBER m_value);
public:
QString m_text;
QString m_value;
};
Q_DECLARE_METATYPE(testStruct)
class AppEngine : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<testStruct *> testStructs READ testStructs NOTIFY testStructsChanged);
public:
explicit AppEngine(QObject *parent = nullptr);
QList<testStruct *> testStructs();
private:
QList<testStruct *> m_testStructs;
signals:
void testStructsChanged();
};
#endif // APPENGINE_H
In appengine.cpp
#include "appengine.h"
AppEngine::AppEngine(QObject *parent)
: QObject{parent}
{
testStruct *newStruct1 = new testStruct;
testStruct *newStruct2 = new testStruct;
newStruct1->m_text = "text1";
newStruct1->m_value = "value1";
newStruct2->m_text = "text2";
newStruct2->m_value = "value2";
m_testStructs << newStruct1 << newStruct2;
qDebug() << "m_testStructs.length():" << m_testStructs.length();
}
QList<testStruct *> AppEngine::testStructs()
{
qDebug() << "testStructs()";
return m_testStructs;
}

Related

Right QML <-> C++ declarative approach

I have some data structure updated in c++ layer. I have to display it in qml and save changes from qml layer to c++ structures. I hope there is a declarative approach to do it but I in desperate to find it.
Here is the part of code:
C++ header:
#ifndef NODEINFO_H
#define NODEINFO_H
#include <QObject>
#include <QString>
class NodeInfo : public QObject {
Q_OBJECT
Q_PROPERTY(QString label READ label WRITE setLabel NOTIFY labelChanged)
public:
NodeInfo(QObject *parent = 0);
virtual ~NodeInfo() {}
const QString& label() const;
void setLabel(const QString& val);
signals:
void labelChanged();
private:
QString d_label;
};
#endif // NODEINFO_H
C++ body:
#include "nodeinfo.h"
#include <QDebug>
NodeInfo::NodeInfo(QObject *parent) : QObject(parent), d_label("Test string") {
}
const QString &NodeInfo::label() const {
qDebug() << "NodeInfo::label: getter";
return d_label;
}
void NodeInfo::setLabel(const QString &val) {
qDebug() << "NodeInfo::label: setter - " << val;
d_label = val;
emit labelChanged();
}
main.cpp
#include <QGuiApplication>
#include <QDebug>
#include <QQmlContext>
#include <QQuickView>
#include <QQmlApplicationEngine>
#include "nodeinfo.h"
int main(int argc, char *argv[]) {
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
// qmlRegisterType<NodeInfo>("NodeInfo", 1, 0, "NodeInfo");
NodeInfo nodeDescr;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("nodeData", &nodeDescr);
const QUrl url(QStringLiteral("qrc:/main.qml"));
engine.load(url);
QObject *root = engine.rootObjects().value(0);
if (QWindow *window = qobject_cast<QWindow *>(root))
window->show();
else
return -1;
return app.exec();
}
Qml code:
import QtQuick 2.15
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
ApplicationWindow {
id: root
width: 360
height: 520
visible: true
// property alias a_label: nodeData.label
Column {
anchors.fill: parent
TextInput {
id: simpleTxt
text: nodeData.label
}
Text {
id: txt
text: nodeData.label
}
Button {
text: "writeProp"
onClicked: nodeData.label = simpleTxt.text
}
// Binding {
// target: nodeData
// property: "label"
// value: simpleTxt.text
// }
}
}
So when I'm editing text in TextInput it should automatically set property in c++ code but it do not. Only if I press button.
There is the Binding way as you see in comments and it works but I it's not a true way I hope.
Let's imagine if I have 15-30 or more data fields in my c++ structure and it's full rubbish if I must do 30 Bindings such way or if I need to write signal/slot on each data field and connect them.
But what is right way?
Any ideas appreciated
A simpler solution is to assign the signal associated to the property text:
Text {
id: txt
text: nodeData.label
onTextChanged: {
if(nodeData.label != simpleTxt.text)
nodeData.label = simpleTxt.text
}
}
text: nodeData.label sets binding nodeData.label --> text (one direction). I.e. text is updated whenever nodeData.label is changed. When the user types some text in the field, this binding is destroyed.
So if you want to update nodeData.label when the user changes text, you need to use onTextChaged event.
Text {
onTextChanged: nodeData.label = text
}
One more note: you need to check if the property is really changed before emitting the appropriate changed signal. So the code should be something like this:
void NodeInfo::setLabel(const QString &val) {
qDebug() << "NodeInfo::label: setter - " << val;
if (d_label != val)
{
d_label = val;
emit labelChanged();
}
}
This will prevent your code from endless binding loops.

Accesing C++ model from QML

I have created a minimal working example. I hope it will be understandable. My problem is that I cannot create a model for my top level item in order to access items further. This is how the classes objects architecture looks like:
CTop
x times CMiddle
y times CBottom
This is a tree architecture. Here is the code:
CBottom.h:
#ifndef CBOTTOM_H
#define CBOTTOM_H
#include <QObject>
#include <QtQml>
class CBottom : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
public:
CBottom(QObject *parent = nullptr) : QObject(parent)
{
}
CBottom(const QString& name, QObject *parent = nullptr) : QObject(parent)
{
qmlRegisterType<CBottom>("Bottom", 1, 0, "Bottom");
m_name = name;
}
QString name()
{
return m_name;
}
void setName(const QString& name)
{
if (name != m_name)
{
m_name = name;
emit nameChanged();
}
}
signals:
void nameChanged();
private:
QString m_name;
};
#endif // CBOTTOM_H
CMiddle.h:
#ifndef CMIDDLE_H
#define CMIDDLE_H
#include <QObject>
#include <QtQml>
#include <QVector>
#include "cbottom.h"
class CMiddle : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
public:
CMiddle(QObject *parent = nullptr) : QObject(parent)
{
}
CMiddle(const QString& name, const QStringList& bottoms, QObject *parent = nullptr) : QObject(parent)
{
qmlRegisterType<CMiddle>("Middle", 1, 0, "Middle");
m_name = name;
foreach (auto bottom, bottoms)
{
m_bottoms.append(new CBottom(bottom));
}
}
QString name()
{
return m_name;
}
void setName(const QString& name)
{
if (name != m_name)
{
m_name = name;
emit nameChanged();
}
}
signals:
void nameChanged();
private:
QString m_name;
QVector<CBottom*> m_bottoms;
};
#endif // CMIDDLE_H
CTop.h:
#ifndef CTOP_H
#define CTOP_H
#include <QObject>
#include <QtQml>
#include "cmiddle.h"
class CTop : public QObject
{
Q_OBJECT
public:
CTop(QObject *parent = nullptr) : QObject(parent)
{
}
CTop(const QStringList& middles, QObject *parent = nullptr) : QObject(parent)
{
qmlRegisterType<CTop>("Top", 1, 0, "Top");
int i = 0;
foreach (auto middle, middles)
{
QStringList bottoms;
bottoms.append("A" + QString(i));
bottoms.append("B" + QString(i));
bottoms.append("C" + QString(i));
i++;
m_middles.append(new CMiddle(middle, bottoms));
}
}
Q_INVOKABLE QVector<CMiddle*>& middles()
{
return m_middles;
}
Q_INVOKABLE CMiddle* middle(const int index)
{
return m_middles[index];
}
private:
QVector<CMiddle*> m_middles;
};
#endif // CTOP_H
main.c:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QString>
#include <QVector>
#include <QStringList>
#include <QVariant>
#include <QQmlContext>
#include "ctop.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QStringList middles;
middles.append("FirstMiddle");
middles.append("SecondMiddle");
CTop* top = new CTop(middles);
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("theTop", QVariant::fromValue(top));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml:
import QtQuick 2.9
import QtQuick.Window 2.2
import Top 1.0
Window
{
width: 600
height: 400
visible: true
Repeater
{
model: theTop.middles();
delegate: txtComp;
}
Component
{
id: txtComp;
Text
{
text: name;
}
}
}
The question is: Why isn't the name of the one of the CMiddle objects displayed in the QML code? I wanted to obtain the CMiddle components (to act as a model) from the exported to QML CTop components. If this code worked, I would then go further and made another model for accessing the CBottom objects within each CMiddle object.
For instance, I noticed that this QML code works:
import QtQuick 2.9
import QtQuick.Window 2.2
import Top 1.0
Window
{
width: 600
height: 400
visible: true
Repeater
{
model: theTop;
delegate: txtComp;
}
Component
{
id: txtComp;
Text
{
text: middle(0).name;
}
}
}
It doesnt make much sense, but shows that the CTop component is exposed correctly to the QML part.
Why cant the output Qvector of CMiddle pointers act as a model in the QML part?
QML does not know QList<CMiddle *>, instead you should use QList<QObject *>:
CTop.h
// ...
Q_INVOKABLE QList<QObject*> middles(){
QList<QObject*> objects;
for(CMiddle *m : qAsConst(m_middles)){
objects << m;
}
return objects;
}
// ...
Also another error is that top should not necessarily be a pointer, and you can pass it without using QVariant::fromValue() since it is a QObject:
main.cpp
// ...
CTop top(middles);
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("theTop", &top);
Also in a Repeater to obtain the item of the model using modelData:
main.qml
//...
Component{
id: txtComp;
Text{
text: modelData.name
}
}
//...
The complete project can be found here

TableView and QAbstracTableModel when calls QQmlApplicationEngine from another class

I am trying to make the model QAbstractTableModel in cpp and connect to qml.
This code works well.
MyModel.h
#ifndef MYMODEL_H
#define MYMODEL_H
#include <QAbstractTableModel>
class MyModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum AnimalRoles {
TypeRole = Qt::UserRole + 1,
SizeRole
};
explicit MyModel(QObject *parent = nullptr);
// Basic functionality:
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
protected:
QHash<int, QByteArray> roleNames() const;
private:
QList<Animal> m_animals;
};
#endif // MYMODEL_H
MyModel.cpp
#include "MyModel.h"
#include <QDebug>
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
qDebug() << __FUNCTION__;
addAnimal(Animal("Wolf", "Medium"));
addAnimal(Animal("Polar bear", "Large"));
addAnimal(Animal("Quoll", "Small"));
}
int MyModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_animals.size();
}
int MyModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 2;
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
qDebug() << __FUNCTION__ << index.row() << index.column() << role;
if (!index.isValid())
return QVariant();
const Animal &animal = m_animals[index.row()];
switch (role) {
case TypeRole:
return animal.type();
case SizeRole:
return animal.size();
default:
break;
}
return QVariant();
}
void MyModel::addAnimal(const Animal &animal)
{
qDebug() << __FUNCTION__;
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_animals << animal;
endInsertRows();
}
QHash<int, QByteArray> MyModel::roleNames() const
{
qDebug() << __FUNCTION__;
QHash<int, QByteArray> roles;
roles[TypeRole] = "type";
roles[SizeRole] = "size";
return roles;
}
main.cpp
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MyModel model;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myModel", &model);
engine.load(QUrl(QStringLiteral("qrc:/resources/qmls/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main_test.qml
import QtQuick 2.0
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
Window {
id: main_view
width: 250
height: 600
visible: true
ListView {
id: list_view
width: 200; height: 250
model: myModel
delegate: Text { text: "Animal Test: " + type + ", " + size }
}
TableView {
id: table_view
objectName: "tableView"
width: 250; height: 250
anchors.top: list_view.bottom
model: myModel
TableViewColumn {
id: type_col
role: "type"
title: "Type"
width: 100
}
TableViewColumn {
id: size_col
role: "size"
title: "Size"
width: 100
}
}
}
It looks like this
But, if I change the main.cpp a little bit, the list view dispaly as normal, but not the table view.
main.cpp
#include "MainView.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MainView mainView;
return app.exec();
}
MainView.h
#ifndef MAINVIEW_H
#define MAINVIEW_H
#include <QObject>
#include <QQmlApplicationEngine>
class MainView: public QObject
{
Q_OBJECT
public:
explicit MainView(QObject *parent=nullptr);
void initializeView();
private:
QQmlApplicationEngine m_engine;
};
#endif // MAINVIEW_H
MainView.cpp
#include "MainView.h"
#include "MyModel.h"
#include <QQmlContext>
MainView::MainView(QObject *parent)
: QObject(parent)
{
initializeView();
}
void MainView::initializeView()
{
MyModel model;
m_engine.rootContext()->setContextProperty("myModel", &model);
m_engine.load(QUrl(QStringLiteral("qrc:/resources/qmls/main_test.qml")));
}
It looks like this.
I really don't understand why this happens. What the difference between ListView and TableView in the second case? And how to fix it, i.e. make data display in the second case? Thank in advance.
The problem is in initializeView, model is a local variable in that scope, and every local variable is deleted from the memory when the function finishes executing. In the first case model will be eliminated when the application is closed, in the second case it will be eliminated when initializeView ends that is when the window is displayed, there are 2 possible solutions:
Create a pointer and to manage the memory we pass to MainView as a parent so that he removes it from memory (this last is a feature of the QObjects):
void MainView::initializeView()
{
MyModel *model = new MyModel(this);
m_engine.rootContext()->setContextProperty("myModel", model);
m_engine.load(QUrl(QStringLiteral("qrc:/resources/qmls/main_test.qml")));
}
Make the model member of the class.
*.h
#ifndef MAINVIEW_H
#define MAINVIEW_H
#include <QObject>
#include <QQmlApplicationEngine>
class MainView: public QObject
{
Q_OBJECT
public:
explicit MainView(QObject *parent=nullptr);
void initializeView();
private:
QQmlApplicationEngine m_engine;
MyModel model{this};
};
#endif // MAINVIEW_H
*.cpp
...
void MainView::initializeView()
{
m_engine.rootContext()->setContextProperty("myModel", &model);
m_engine.load(QUrl(QStringLiteral("qrc:/resources/qmls/main_test.qml")));
}
To understand the behavior I have added more points of impression:
MyModel::~MyModel()
{
qDebug()<<"destructor";
}
TableView {
...
Component.onCompleted: {
console.log("completed table")
if(!timer.running)
timer.running = true
}
}
ListView {
...
Component.onCompleted: {
console.log("completed list")
if(!timer.running)
timer.running = true
}
}
Timer {
id: timer
interval: 0;
onTriggered: console.log(myModel, table_view.model, list_view.model)
}
And I get the following:
MyModel
addAnimal
addAnimal
addAnimal
roleNames
data 0 0 257
data 0 0 258
data 1 0 257
data 1 0 258
data 2 0 257
data 2 0 258
roleNames
qml: completed list
data 0 0 257
data 0 0 258
qml: completed table
destructor
qml: null null null
We note that ListView manages to load the data, whereas TableView in the middle of the load is called the destructor.
Possible explanation: I think that the ListView stores the data making a copy of them and only updates when the model notifies, should also be notified when the model is deleted to clean the data, it seems that this is a bug. On the other hand, TableView, being at the moment of loading and deleting the model, is null, so it is notified and cleans the data.
Doing another test:
void MainView::initializeView()
{
MyModel *model = new MyModel;
m_engine.rootContext()->setContextProperty("myModel", model);
m_engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QTimer::singleShot(1000, model, &MyModel::deleteLater);
}
It is observed that both load the data correctly, and after a second the model is destroyed, but the one that is only notified is the TableView since it is the only one that cleans the data shown, and ListView does not.
my conclusion that it is a ListView bug.

How can I display a QStringList in C++ to a QML ListView

So I'm new to Qt and I'm trying to improve my C++ skills, so I decided to start a project where I can search items in a QStringList using a textfield. I got the search function working and I was able to move the result of the search into another QStringList, where I can use it to display to the user in a function that is declared as a "public slot".
The main Idea is that the list will auto update as soon as the user enters a character into the textfield, which it already does. So I managed to get the resulted list into the Slot function to be able to display a different list every time and character gets typed in the textfield.
In the function where I pass in the list of search results, I am trying to use this
m_context->setContextProperty("resultModel",QVariant::fromValue(m_resultList));
where resultModel is the name of my model in QML and m_resultList is where the results of the search are being stored, to display the list in the ListView. My program compiles but it crashes after I run it.
So, my true question is: Is there any way that I can display a C++ QStringList not in the main.cpp into a QML ListView?
The reason why I'm asking for it to not be in the main is because I tried to use that same line above in the main.cpp with a hard coded QStringList and the list was able to display, so there must be an issue with it not being in the main. Also because I would not be able to use the slot function in SearchClass to auto update.
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
#include "searchclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<SearchClass>("b9c.backend", 1, 0, "BackEnd");
QQmlApplicationEngine engine;
SearchClass obj;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QQmlContext *context = engine.rootContext();
obj.getContext(context);
//the line below works if provided with a qstringlist
//context->setContextProperty("resultModel", QVariant::fromValue(resultList));
return app.exec();
}
SearchClass.h
#ifndef SEARCHCLASS_H
#define SEARCHCLASS_H
#include <QObject>
#include <QQmlContext>
class SearchClass : public QObject
{
Q_OBJECT
Q_PROPERTY(QString userSearch READ userSearch WRITE setUserSearch NOTIFY userSearchChanged)
public:
SearchClass(QObject *parent = 0);
QStringList resultList;
QString userSearch();
void setUserSearch(QString &userSearch);
void getFilenameAndInput(QString inputString);
QString CompareInputAndFilename(QString inputString, QString filename);
QStringList getFileName();
//get context
void getContext(QQmlContext *context);
signals:
void userSearchChanged();
public slots:
void setUserSearch();
private:
QStringList m_resultList;
QString m_userSearch;
QQmlContext* m_context;
};
#endif // SEARCHCLASS_H
SearchClass.cpp
#include "searchclass.h"
#include <QDebug>
#include <QQmlContext>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
SearchClass::SearchClass(QObject *parent) : QObject(parent)
{
connect(this, SIGNAL(userSearchChanged()), this, SLOT(setUserSearch()));
}
//the result should be displayed in this SLOT when ever the user types in a character into the textfield
void SearchClass::setUserSearch(){
qDebug() << "SLOT: " << m_resultList;
//The line below makes the program crash. It works when implemented in the main.cpp
// m_context->setContextProperty("resultModel", QVariant::fromValue(m_resultList));
}
QString SearchClass::userSearch()
{
return m_userSearch;
}
void SearchClass::setUserSearch(QString &userSearch)
{
if (userSearch == m_userSearch)
return;
m_userSearch = userSearch;
qDebug() << "Input: " <<m_userSearch;
getFilenameAndInput(m_userSearch);
emit userSearchChanged();
}
QStringList SearchClass::getFileName(){
//Returns the items that will be searched for...
}
void SearchClass::getFilenameAndInput(QString inputString){
//Puts the search results into class variable m_resultList...
m_resultList = resultList;
}
QString SearchClass::CompareInputAndFilename(QString inputString, QString filename){
//Search processing...
}
//gets context to use setProperty in the above signal, but it crashes
void SearchClass::getContext(QQmlContext *context){
m_context = context;
}
main.qml
import QtQuick 2.6
import QtQuick.Controls 2.0
import b9c.backend 1.0
import QtQuick.Window 2.2
ApplicationWindow {
id: root
width: 300
height: 480
visible: true
BackEnd { id: backend }
TextField {
id: txtfield
text: backend.userSearch
placeholderText: qsTr("Search...")
width: parent.width
onTextChanged: backend.userSearch = text
}
ListView {
id:view
height: parent.height
width: parent.width
y: 5 + txtfield.height
model: resultModel
delegate: Rectangle {
border.color: "lightblue"
height: 25
width: parent.width
Text {
anchors.centerIn: parent
text: modelData
}
}
}
}
You are doing it wrong. In every possible way. You even name getContext() the function that actually sets the context.
m_resultList is never set to anything in that code you have provided. So there is no way to tell you why your application is crashing, because the actual data is a mystery.
You also have a QObject derived class - your SearchClass. So you should expose that as a context property, and then have the string list interfaced to QML by being implemented as a Q_PROPERTY of SearchClass.
Here is a simple example:
// the equivalent of your SearchClass
class Test : public QObject {
Q_OBJECT
Q_PROPERTY(QStringList model MEMBER m_model NOTIFY modelChanged)
QStringList m_model;
public slots:
void setModel(QString m) {
m_model = m.split(" ");
modelChanged();
}
signals:
void modelChanged();
};
// in main.cpp
Test t;
engine.rootContext()->setContextProperty("Test", &t);
// in main.qml
Column {
TextField {
onTextChanged: Test.setModel(text)
}
ListView {
width: 200; height: 300
spacing: 5
model: Test.model
delegate: Rectangle {
height: 25
width: 200
color: "lightgray"
Text { text: modelData; anchors.centerIn: parent }
}
}
}
As you type the text string is sent to Test::setModel(), which then splits it into space separated tokens and sets the QStringList, which is used as a model source for the list view.

QString exchange in qml through c++

this example is supposed to read the string from TextInput and display it in another Rectangle on click of the mouse. However, it does not. Why?
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QObject>
#include <QString>
class MainWindow : public QDeclarativeView
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
class Data : public QObject
{
Q_OBJECT
Q_PROPERTY(QString teamName READ getTeamName WRITE setTeamName NOTIFY nameChanged)
public:
Data(QObject *parent = 0);
~Data();
public:
QString getTeamName();
void setTeamName(QString &);
signals:
void nameChanged();
private:
QString n_teamName;
};
#endif // MAINWINDOW_H
//mainwindow.cpp
#include "mainwindow.h"
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QString>
#include <QObject>
MainWindow::MainWindow(QWidget *parent)
: QDeclarativeView(parent)
{
}
MainWindow::~MainWindow()
{
}
Data::Data(QObject *parent) : QObject(parent)
{
//n_teamName = "Ahoj";
}
Data::~Data(){
}
QString Data::getTeamName(){
return n_teamName;
}
void Data::setTeamName(QString &newName){
if(newName != n_teamName){
n_teamName = newName;
emit nameChanged();
}
}
//main.cpp
#include "mainwindow.h"
#include <qdeclarative.h>
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
Data d;
qmlRegisterType<Data>("NData", 1, 0, "Data");
w.rootContext()->setContextProperty("data", &d);
w.setSource(QUrl::fromLocalFile("../klik/Main.qml"));
w.show();
return a.exec();
}
//main.qml
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import NData 1.0
Rectangle {
id: root
width: 600
height: 400
Rectangle{
id: text
...
TextInput{
anchors.fill: text
anchors.margins: 3
focus: true
}
}
Rectangle{
...
Text{
id: copyText
anchors.centerIn: copy
text: data.setTeamName()
}
}
Rectangle{
id: klik
...
MouseArea{
...
onClicked: {
copyText.text = data.teamName
}
}
}
}
It lets out the error: TypeError: Result of expression 'data.setTeamName' [undefined] is not a function.
Main.qml:51: Error: Cannot assign [undefined] to QString
teamName is a property of data, so simply use assign operator like data.teamName = 'some text';
Probably you should add id field to your TextInput like
TextInput{
id: textInput
anchors.fill: text
anchors.margins: 3
focus: true
}
And change onClicked, so
MouseArea{
...
onClicked: {
data.teamName = textInput.text
copyText.text = data.teamName // copyText.text = textInput.text is fine too
}
}
I believe your actual exception is due to the following line
text: data.setTeamName()
setTeamName is a private function on your data object, that is not exposed as a slot, and is thus undefined when called and assigned to text. Nevermind the fact that it makes no sense to call the set when you are performing an assignment. I'm assuming this was supposed to be data.getTeamName().