Accesing C++ model from QML - c++

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

Related

Best way to create Elements dynamically in QML based on C++ QMap

This seemed like a simple task at first, but honestly I am struggling. I have a Map of profiles I load at startup, and profiles can be added and deleted at runtime. Those profiles need to be listed as RadioButtons or some other element for selection/editing in my UI.
I've tried using createQMLObject() while looping trough a QVariantMap getter:
profile.h
#ifndef PROFILE_H
#define PROFILE_H
#include <QObject>
class Profile final : public QObject
{
Q_OBJECT
public:
Profile(QObject *parent = nullptr);
~Profile(){}
Profile(QString profileName = "default", QObject *parent = nullptr);
QString getProfileName() const;
void setProfileName(const QString &value);
private:
QString profileName;
};
#endif // PROFILE_H
profile.cpp
#include "profile.h"
Profile::Profile(QString profileName, QObject *parent)
: QObject(parent), profileName{ profileName }{}
QString Profile::getProfileName() const
{
return profileName;
}
void Profile::setProfileName(const QString &value)
{
profileName = value;
}
controller.h
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "profile.h"
#include <QObject>
#include <QQmlEngine>
class Controller : public QObject
{
Q_OBJECT
public:
Controller(QObject *parent = nullptr);
~Controller(){}
static QObject* controllerSingletonProvider(QQmlEngine *engine, QJSEngine *scriptEngine);
static Controller* instance();
Q_INVOKABLE void addProfile(QString profileName);
Q_INVOKABLE QVariantList getLoadedProfiles(){
QVariantList rval;
foreach (QString key, loadedProfiles.keys()) {
rval.append(QVariant::fromValue<Profile*>(loadedProfiles[key].get()));
}
return rval;
};
private:
QMap<QString, std::shared_ptr<Profile>> loadedProfiles;
signals:
};
#endif // CONTROLLER_H
controller.cpp
#include "controller.h"
Controller::Controller(QObject *parent) : QObject(parent){}
void Controller::addProfile(QString profileName)
{
std::shared_ptr<Profile> profile{std::make_shared<Profile>(profileName)};
loadedProfiles[profile->getProfileName()] = profile;
}
QObject* Controller::controllerSingletonProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
return Controller::instance();
}
Controller* Controller::instance(){
static Controller* controller = new Controller();
return controller;
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <controller.h>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
qmlRegisterSingletonType<Controller>("com.controller", 1, 0, "Controller", Controller::controllerSingletonProvider);
Controller::instance()->addProfile("Profile1");
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();
}
main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import com.controller 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Column {
id: radioButtonColumn
Component.onCompleted: {
for(var profile in Controller.getLoadedProfiles()){
var obj = Qt.createQmlObject('import QtQuick 2.12; RadioButton { id: '+ profile.getProfileName() +';
text: '+ profile.getProfileName() +'; }', radioButtonColumn, "dynamicSnippet1");
}
}
}
}
I've tried using a signal sent from my Controller Singleton using Connections, but the parameter of the signal does not arrive. I can however call my Controllers c++ functions from qml. I'll only post the changes to the previous code sample:
main.qml changes:
Connections {
target: Controller
onProfileAdded: {
var obj = Qt.createQmlObject('import QtQuick 2.12; RadioButton { id: '+ profileName +';
text: '+ profileName +'; }', radioButtonColumn, "dynamicSnippet1");
console.log("Value changed")
}
}
controller.h changes:
signals:
void profileAdded(QString &profileName);
};
controller.cpp changes:
void Controller::addProfile(QString profileName)
{
std::shared_ptr<Profile> profile{std::make_shared<Profile>(profileName)};
loadedProfiles[profile->getProfileName()] = profile;
emit profileAdded(profileName);
}
main.cpp changes:
engine.load(url);
Controller::instance()->addProfile("Profile2");
return app.exec();
Edit: Curious, that I had to change my onProfileAdded in controller.h to profileAdded for the signal to work. However, I still do not receive the parameter profileName in my qml.
I would like to ask what is the best way to handle a requirement like this. Maybe there is another, simpler way?
Im new to both c++ and QT, so please bear with my perhaps trivial question, but my research didnt yield me anything, that I could understand at least.

Change QML Label text from a C++ function

I have a Label in QML and I want to change its text value when I click on a button. I have tried many different ways to achieve this, but nothing seems to work properly. I have used QObject::setProperty() and it seems to work when I print the new text value with qDebug(), but it does not refresh on the GUI. What am I doing wrong?
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSettings>
#include <QQuickStyle>
#include <QtQuickControls2>
#include <QQmlContext>
#include <QIcon>
#include "Controllers/Network/network.hpp"
#include "Controllers/NFC/nfc.hpp"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QIcon::setThemeName("gallery");
QQuickStyle::setStyle("Material");
// Property bindings:
qmlRegisterType<RFS::Communication::Network>("rfs.communication.network", 1, 0, "Network");
qmlRegisterType<RFS::Communication::NFC>("rfs.communication.nfc", 1, 0, "NFC");
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("availableStyles", QQuickStyle::availableStyles());
engine.load(QUrl("qrc:/main.qml"));
if (engine.rootObjects().isEmpty()) return -1;
return app.exec();
}
nfc.hpp:
#include <QObject>
#include <QtNfc/qnearfieldmanager.h>
#include <QtNfc/qnearfieldtarget.h>
namespace RFS::Communication
{
class NFC : public QObject
{
Q_OBJECT
public:
explicit NFC(QObject *parent = nullptr);
Q_INVOKABLE bool getStatus() { return pairingStatus; }
Q_INVOKABLE void changeTextValue();
private:
bool pairingStatus;
};
}
nfc.cpp:
#include <QtQuick>
#include <QQuickView>
#include "Controllers/NFC/nfc.hpp"
void RFS::Communication::NFC::changeTextValue()
{
QQuickView view;
view.setSource(QUrl("qrc:/Views/overview.qml"));
QObject *rootObject = view.rootObject();
QList<QObject*> list = rootObject->findChildren<QObject*>();
QObject *testLabel = rootObject->findChild<QObject*>("testLabel");
qDebug() << "Object" << testLabel->property("text"); // Successfully prints old value
testLabel->setProperty("text", "test1");
qDebug() << "Object" << testLabel->property("text"); // Successfully prints new value
QQmlProperty(testLabel, "text").write("test2");
qDebug() << "Object" << testLabel->property("text"); // Successfully prints new value
}
overview.qml:
import QtQuick 2.12
import QtQuick.Controls 2.12
import rfs.communication.nfc 1.0
Page {
id: page
NFC {
id: nfc
}
SwipeView {
id: swipeView
anchors.fill: parent
currentIndex: tabBar.currentIndex
Pane {
id: overviewTab
width: swipeView.width
height: swipeView.height
Button {
id: pairButton
text: qsTr("Pair new receiver")
onClicked: {
nfc.changeTextValue()
}
}
Label {
id: testLabel
objectName: "testLabel"
text: "hei" // I want to change this value
}
}
}
}
Is there any better way to achieve this? Thanks a lot in advance.
Anyone looking for a simple solution, I just came up with this trying to achieve changing label's text on c++ side by pressing a button in QML
Add to main.cpp:
Backend backend;
engine.rootContext()->setContextProperty("backend", &backend);
Create a new class (backend.h & backend.cpp)
In backend.h:
#ifndef CONTROLLERS_H
#define CONTROLLERS_H
#include <Qt>
#include <QObject>
#include <QCoreApplication>
#include <QWindow>
#include <QString>
class Backend : public QObject
{
Q_OBJECT
public:
explicit Backend(QObject *parent = nullptr);
public slots:
void setText();
QString getText();
};
#endif // CONTROLLERS_H
In backend.cpp:
#include "backend.h"
QString text = ""; // don't forget this
Backend::Backend(QObject *parent) : QObject(parent)
{
}
QString Backend::getText()
{
return text; //returns the text you set or didnt in setText()
}
void Backend::setText()
{
text = "text"; // or do anything you want with global QString text
}
In QML:
Label{
id: myLabel
}
Button{
id: myButton
onClicked:{
backend.setText()
myLabel.text = backend.getText()
}
}

Instantiate QML From C++

I have 2 classes, MyApp and MyAppView. MyApp class will hold other classes and the implementation will be here. (you can call it Manager class or System class). MyAppView class only interacts with main.qml like it'll have lots of "Q_PROPERTY"ies. I think you understand the point. I don't want MyApp will have "Q_PROPERTY"ies.
The scenerio is as the following;
//------------------------------------
//---------------------------main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "myapp.h"
#include "myappview.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<MyAppView>("org.myappview", 1, 0, "MyAppView");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
MyApp myApp;
return app.exec();
}
//------------------------------------
//---------------------------myappview.h
#include <QObject>
class MyAppView : QObject
{
Q_OBJECT
Q_PROPERTY(QString myString READ getMyString NOTIFY myStringChanged)
public:
MyAppView();
QString getMyString() { return m_myString; }
void setMyString(QString newString)
{
m_myString = newString;
emit myStringChanged;
}
signals:
void myStringChanged();
private:
QString m_myString;
}
//------------------------------------
//---------------------------main.qml
import QtQuick 2.0
import QtQuick.Window 2.0
import org.myappview 1.0
Window {
visible: true
MyAppView {
id: backend
}
Text {
text: qsTr(backend.myString)
}
}
//------------------------------------
//---------------------------myapp.h
#include <QObject>
#include "myappview.h"
class MyApp : QObject
{
Q_OBJECT
public:
MyApp();
private:
MyAppView appView;
void changeMyStringInAppView()
{
// This will automatically update main.qml
appView.setMyString("This is new string");
}
}
Also it is okay to reaching existing QML instance from MyApp, instead of instantiating QML from MyApp. So the main point is instantiating or reaching View class from Manager class so that I can control it easily. Maybe at some part, my logic is wrong. Please tell me if I am. I'm okay with all the suggestions.
The problem in your code is that the MyAppView of MyApp is different from the one created in QML, so if you update the appView text it will not be reflected in the backend text, so the solution is to expose an object from MyApp to QML with setContextProperty() and will call a function to establish the MyAppView created in QML (Keep in mind to create only one MyApp but you will have the same problem)
// myappview.h
#ifndef MYAPPVIEW_H
#define MYAPPVIEW_H
#include <QObject>
class MyAppView : public QObject
{
Q_OBJECT
Q_PROPERTY(QString myString READ getMyString NOTIFY myStringChanged)
public:
explicit MyAppView(QObject *parent = nullptr) : QObject(parent)
{}
QString getMyString() const { return m_myString; }
void setMyString(const QString & newString)
{
if(m_myString != newString){
m_myString = newString;
emit myStringChanged();
}
}
signals:
void myStringChanged();
private:
QString m_myString;
};
#endif // MYAPPVIEW_H
// myapp.h
#ifndef MYAPP_H
#define MYAPP_H
#include "myappview.h"
#include <QObject>
class MyApp : public QObject
{
Q_OBJECT
public:
explicit MyApp(QObject *parent = nullptr) : QObject(parent),
appView(nullptr)
{}
Q_INVOKABLE void setAppView(MyAppView *value){
appView = value;
}
void changeMyStringInAppView()
{
if(appView)
appView->setMyString("This is new string");
}
private:
MyAppView *appView;
};
#endif // MYAPP_H
// main.cpp
#include "myapp.h"
#include "myappview.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<MyAppView>("org.myappview", 1, 0, "MyAppView");
MyApp myapp;
QTimer::singleShot(1000, &myapp, &MyApp::changeMyStringInAppView);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("myapp", &myapp);
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 org.myappview 1.0
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
MyAppView {
id: backend
}
Text {
text: qsTr(backend.myString)
}
Component.onCompleted: myapp.setAppView(backend)
}

Exposing QList<customobj *> to QML

I am trying to expose QList with custom objects (Sample) into QML. Whenever I store those custom objects (they inherits form QObject) into QList<QObject *>, they show up, but without info, but when I try expose them as a QList<Sample *>, they don't.
sample.h
class Sample : public QObject
{
Q_OBJECT
Q_PROPERTY(QString getVar READ getVar WRITE setVar NOTIFY varChanged)
public:
explicit Sample();
//! Returns var
QString getVar() const { return var; }
//! Sets var
void setVar(const QString &a);
signals:
varChanged();
protected:
QString var;
};
Class containing list looks like this
samplecontrol.h
class SampleManager : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<Sample *> getSampleList READ getSampleList NOTIFY sampleListChanged)
public:
SampleManager(const QString &path);
//! Returns sample list
QList<Sample *> getSampleList() const { return sampleList_; }
signals:
sampleListChanged();
protected:
QList<Sample *> sampleList_;
};
I am setting context with
view_->rootContext()->setContextProperty("slabGridModel", QVariant::fromValue(samplecontrol.getSampleList()));
As I said, when i tired
QList<QObject *> datalist;
datalist.append(sampleManager.getSampleList().first());
datalist.append(sampleManager.getSampleList().last());
it worked. How can I make it work with QList<Sample *>?
Thanks for your help!
You can pass a list of QObjects, but the problem is that it will not notify the view if more elements are added, if you want the view to be notified you must use a model that inherits from QAbstractItemModel. On the other hand how are you doing the datamodel as qproperty it is better to expose the SampleManager:
samplemodel.h
#ifndef SAMPLEMODEL_H
#define SAMPLEMODEL_H
#include "sample.h"
#include <QAbstractListModel>
class SampleModel : public QAbstractListModel
{
Q_OBJECT
public:
using QAbstractListModel::QAbstractListModel;
~SampleModel(){
qDeleteAll(mSamples);
mSamples.clear();
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override{
if (parent.isValid())
return 0;
return mSamples.size();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override{
if (!index.isValid())
return QVariant();
if(role == Qt::UserRole){
Sample *sample = mSamples[index.row()];
return QVariant::fromValue(sample);
}
return QVariant();
}
void appendSample(Sample * sample)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
mSamples << sample;
endInsertRows();
}
QHash<int, QByteArray> roleNames() const{
QHash<int, QByteArray> roles;
roles[Qt::UserRole] = "sample";
return roles;
}
private:
QList<Sample *> mSamples;
};
#endif // SAMPLEMODEL_H
samplemanager.h
#ifndef SAMPLEMANAGER_H
#define SAMPLEMANAGER_H
#include "samplemodel.h"
#include <QObject>
class SampleManager : public QObject
{
Q_OBJECT
Q_PROPERTY(SampleModel* model READ model WRITE setModel NOTIFY modelChanged)
public:
using QObject::QObject;
SampleModel *model() const{
return mModel.get();
}
void setModel(SampleModel *model){
if(mModel.get() == model)
return;
mModel.reset(model);
}
signals:
void modelChanged();
private:
QScopedPointer<SampleModel> mModel;
};
#endif // SAMPLEMANAGER_H
main.cpp
#include "samplemanager.h"
#include "samplemodel.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTime>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
SampleManager manager;
manager.setModel(new SampleModel);
// test
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&manager](){
manager.model()->appendSample(new Sample(QTime::currentTime().toString()));
});
timer.start(1000);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("manager", &manager);
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
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
GridView {
anchors.fill: parent
model: manager.model
delegate:
Rectangle {
width: 100
height: 100
color: "darkgray"
Text {
text: sample.getVar
anchors.centerIn: parent
}
}
}
}
The complete example can be found in the following link.

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().