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().
Related
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()
}
}
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
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)
}
I created a QML class like
import QtQuick 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Extras 1.4
Rectangle {
width: 80
height: 200
property double myVal: 15
Timer {
running: true
repeat: true
interval: 1
onTriggered: gauge.value = myVal
}
Gauge {
objectName: "gauge"
id: gauge
anchors.fill: parent
anchors.margins: 10
value: myVal
Behavior on value {
NumberAnimation {
duration: 1000
}
}
style: GaugeStyle {
valueBar: Rectangle {
implicitWidth: 16
color: Qt.rgba(gauge.value / gauge.maximumValue, 0, 1 - gauge.value / gauge.maximumValue, 1)
}
}
}
}
and I want to change value from my c++ file. To do this, I created a method which is setDataToGauge() and this method is like
void MainWindow::setDataToGauge(double newVal){
QQmlApplicationEngine engine;
QQmlComponent component(&engine, QUrl::fromLocalFile("gauge.qml"));
QObject object = component.create();
QObject *myGauge = object->findChild<QObject*>("gauge");
if(myGauge){
myGauge->setProperty("value",newVal);
qDebug() << myGauge->property("value");
}
}
this. However, it doesn't change the value of gauge. I tried different methods but it couldn't find the solution. When I drop
Behavior on value {
NumberAnimation {
duration: 1000
}
}
this part from QML file value is changing but view of gauge is not changing.
Also, I am adding to full code of my c++ file
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDateTime>
#include <QtQuickWidgets/QQuickWidget>
#include <QtQml>
#include <QObject>
QObject *object;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_serial(new QSerialPort(this))
{
ui->setupUi(this);
ui->gaugeWidget->setSource(QUrl::fromLocalFile("gauge.qml"));
ui->gaugeWidget->setUpdatesEnabled(true);
QQmlApplicationEngine engine;
QQmlComponent component(&engine, QUrl::fromLocalFile("gauge.qml"));
object = component.create();
setDataToGauge(60.0);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setDataToGauge(double newVal){
QObject *myGauge = object->findChild<QObject*>("gauge");
if(myGauge){
QQmlProperty::write(myGauge, "value", newVal);
qDebug() << myGauge->property("value");
}
}
What is the problem in there?
In your attempt of solution you are creating another gauge, and that gauge is not shown because the QQmlApplicationEngine is a local variable that will be deleted when it finishes executing, in addition QQmlApplicationEngine expects a Window or ApplicationWindow, not an Item like Rectangle.
On the other hand it is advisable to use a qresource to store the .qml because otherwise you will have to copy them every time you compile the side of your executable.
It is also not recommended to access QML objects from C ++, it is better to export a C ++ object to QML using setContextProperty().
A simple solution is to create a signal, the signal is connected through Connections::
*.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
void setDataToGauge(double newVal);
signals:
void dataGaugeChanged(double dataToGauge); // signal
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
*.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QQmlEngine>
#include <QQmlContext>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->gaugeWidget->engine()->rootContext()->setContextProperty("MainWindow", this);
ui->gaugeWidget->setSource(QUrl("qrc:/gauge.qml"));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setDataToGauge(double newVal){
emit dataGaugeChanged(newVal);
}
gauge.qml
import QtQuick 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Extras 1.4
Rectangle {
width: 80
height: 200
Gauge {
id: gauge
anchors.fill: parent
anchors.margins: 10
Behavior on value {
NumberAnimation {
duration: 1000
}
}
style: GaugeStyle {
valueBar: Rectangle {
implicitWidth: 16
color: Qt.rgba(gauge.value / gauge.maximumValue, 0, 1 - gauge.value / gauge.maximumValue, 1)
}
}
}
Connections{
target: MainWindow
onDataGaugeChanged: gauge.value = dataToGauge
}
}
Another option is to create a Q_PROPERTY and make a binding:
*.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
Q_PROPERTY(double dataGauge READ dataGauge WRITE setDataGauge NOTIFY dataGaugeChanged)
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
double dataGauge() const;
void setDataGauge(double dataGauge);
signals:
void dataGaugeChanged();
private:
Ui::MainWindow *ui;
double mDataGauge;
};
#endif // MAINWINDOW_H
*.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QQmlEngine>
#include <QQmlContext>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->gaugeWidget->engine()->rootContext()->setContextProperty("MainWindow", this);
ui->gaugeWidget->setSource(QUrl("qrc:/gauge.qml"));
}
MainWindow::~MainWindow()
{
delete ui;
}
double MainWindow::dataGauge() const
{
return mDataGauge;
}
void MainWindow::setDataGauge(double dataGauge)
{
if(mDataGauge == dataGauge)
return;
mDataGauge = dataGauge;
emit dataGaugeChanged();
}
*.qml
import QtQuick 2.2
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4
import QtQuick.Extras 1.4
Rectangle {
width: 80
height: 200
Gauge {
id: gauge
anchors.fill: parent
anchors.margins: 10
value: MainWindow.dataGauge // binding
Behavior on value {
NumberAnimation {
duration: 1000
}
}
style: GaugeStyle {
valueBar: Rectangle {
implicitWidth: 16
color: Qt.rgba(gauge.value / gauge.maximumValue, 0, 1 - gauge.value / gauge.maximumValue, 1)
}
}
}
}
Both solutions can be found in the following link.
I am trying to send a list from QML to c++. I've tried with a string and an integer with success but when I try with a QVariant I get the error:
QObject::connect: No such slot MyClass::cppSlot(QVariant) in ../test_2206/main.cpp:31
My main.qml
import QtQuick 2.4
import QtQuick.Layouts 1.1
import Material.ListItems 0.1 as ListItem
import Material.Extras 0.1
import QtQuick.Controls 1.3 as QuickControls
import QtQuick.Controls 1.4
import Material 0.2
Window {
visible: true
property var listCloud: ["nuage1", "nuage2", "nuage3", "nuage4"]
id: item
width: 100; height: 100
signal qmlSignal(variant msg)
/* MouseArea {
anchors.fill: parent
onClicked: item.qmlSignal("Hello from QML")
}*/
Rectangle{
id:sousRect
color:"red"
width:100; height:100
Button{
id:buttonTest
onClicked: {
item.qmlSignal(listCloud)
}
}
}
}
My main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlProperty>
#include <QQmlComponent>
#include <QDebug>
#include "myclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));
QObject *object = component.create();
MyClass myClass;
QObject::connect(object, SIGNAL(qmlSignal(QVariant)),
&myClass, SLOT(cppSlot(QVariant)));
return app.exec();
}
My myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QDebug>
#include <QString>
#include <QList>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
signals:
public slots:
void cppSlot(QVariant &msg);
};
#endif // MYCLASS_H
My myclass.cpp
#include "myclass.h"
MyClass::MyClass(QObject *parent):
QObject(parent)
{
}
void MyClass::cppSlot(QVariant &msg){
qDebug() << "c++: bien reçu chef " << msg;
}
I don't understand why I can't put a QVariant parameter in this signal.
Any help is welcome :)
Change your slot to receive his parameter by value, rather than by reference. Like this:
void cppSlot(QVariant msg);
I think it has something to do with QML refusing to pass Window's property by reference. Anyway, Qt often sends signal by-value even if your signal/slot signature[s] declare arguments by-reference. For more on the topic see this and that
Don't use references between QML and C++, they won't work.
void cppSlot(QVariant & msg);
You can also create Q_INVOKABLE function in C++ and call it directly from QML. Here is how this looks like:
main.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlProperty>
#include <QQmlComponent>
#include <QDebug>
#include "myclass.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
auto myobject = new MyClass(&app);
engine.rootContext()->setContextProperty(QStringLiteral("myobject"), myobject);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
{
return -1;
}
return app.exec();
}
mycass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QDebug>
#include <QString>
#include <QList>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
Q_INVOKABLE void cppSlot(QVariant msg);
};
#endif // MYCLASS_H
myclass.cpp:
#include "myclass.h"
MyClass::MyClass(QObject *parent):QObject(parent){}
void MyClass::cppSlot(QVariant msg)
{
qDebug() << "c++: bien reçu chef " << msg;
}
main.qml:
import QtQuick 2.4
import QtQuick.Layouts 1.1
import Material.ListItems 0.1 as ListItem
import Material.Extras 0.1
import QtQuick.Controls 1.3 as QuickControls
import QtQuick.Controls 1.4
import Material 0.2
Window
{
visible: true
property var listCloud: ["nuage1", "nuage2", "nuage3", "nuage4"]
id: item
width: 100; height: 100
Rectangle
{
id:sousRect
color:"red"
width:100; height:100
Button
{
id:buttonTest
onClicked: myobject.cppSlot(listCloud)
}
}
}
But if you like to use SIGNAL SLOTS there is Connections Object in QML. Your main.qml will look then like that:
Window
{
visible: true
property var listCloud: ["nuage1", "nuage2", "nuage3", "nuage4"]
id: item
width: 100; height: 100
Connections
{
target: buttonTest
onClicked: myobject.cppSlot(listCloud)
}
Rectangle
{
id:sousRect
color:"red"
width:100; height:100
Button
{
id:buttonTest
}
}
}
Q_INVOKABLE is nothing else as an public SLOT, it will be called through meta-object system.