I want to change object defined in QML from a slot in C++. In slot startButtonClicked() I start timer which every second calls slot getData(). How can I change the label defined in QML from C++ slot genData()? Now I am able to change in only from main.cpp
class LogicClass : public QObject
{
Q_OBJECT
public:
LogicClass();
~LogicClass();
public slots:
void startButtonClicked(const QVariant &v);
void getData();
};
main:
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
class LogicClass logicClass;
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
QObject *rootObject = engine.rootObjects().first();
QObject *qmlObject = rootObject->findChild<QObject*>("startButton");
QObject::connect(qmlObject, SIGNAL(qmlSignal(QVariant)),&logicClass, SLOT(startButtonClicked(QVariant)));
return app.exec();
}
qml:
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
ApplicationWindow {
id: window
objectName: "window"
visible: true
width: 640
height: 520
title: qsTr("MY app")
Button {
id: startButton
objectName: "startButton"
x: 25
text: qsTr("Start")
signal qmlSignal(var anObject)
MouseArea {
anchors.fill: parent
onClicked: startButton.qmlSignal(startButton)
}
}
Label {
objectName: "latitudeLabelValue"
id: latitudeLabelValue
y: 478
width: 50
text: qsTr("")
}
}
}
You have to use the setProperty method:
QObject *lblLatitute = rootObject->findChild<QObject*>("latitudeLabelValue");
lblLatitute->setProperty("text", "234.234");
But consider to use the model/view/delegate paradigm.
Passing a pointer to rootObject to LogicClass() can be a solution.
QObject *rootObject = engine.rootObjects().first();
class LogicClass logicClass(rootObject);
Save it as a aparameter of a class, and use it. this->rootObject->rootObject->findChild<QObject*>("latitudeLabelValue");
and then the setProperty() function.
Related
I'm very new to Qt, and right now struggling to figure out how to change the index of the SwipeView through a different C++ class. I'd like to make some kind of a signal that emits from the C++ class saying "Swipe Right" or something like that, and having the SwipeView respond. I'm also new to signals and slots, so I might be misunderstanding how they work.
When you want to control a QML element from C ++ the best strategy is to create a QObject that has Q_PROPERTY, slot and signals and export it to QML through setContextProperty(), and perform the direct binding or use Connections to connect the signals, in this case it is only necessary to emit a signal and connect it in QML.
In the following example I show how to change to the right or left using QPushButton:
main.cpp
#include <QApplication>
#include <QPushButton>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QHBoxLayout>
class SwipeManager: public QObject{
Q_OBJECT
public:
using QObject::QObject;
public slots:
void moveToRight(){
emit toRight();
}
void moveToLeft(){
emit toLeft();
}
signals:
void toRight();
void toLeft();
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
SwipeManager manager;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("manager", &manager);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
QWidget w;
QPushButton left("to left");
QPushButton right("to right");
QHBoxLayout *lay = new QHBoxLayout(&w);
lay->addWidget(&left);
lay->addWidget(&right);
QObject::connect(&left, &QPushButton::clicked, &manager, &SwipeManager::moveToLeft);
QObject::connect(&right, &QPushButton::clicked, &manager, &SwipeManager::moveToRight);
w.show();
return app.exec();
}
#include "main.moc"
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4
Window {
visible: true
width: 640
height: 480
title: qsTr("SwipeView Test")
SwipeView {
id: view
anchors.fill: parent
currentIndex: 4
Repeater {
model: 10
Loader {
active: SwipeView.isCurrentItem || SwipeView.isNextItem || SwipeView.isPreviousItem
sourceComponent: Item{
Text {
text: "Page: "+index
anchors.centerIn: parent
}
}
}
}
}
Connections{
target: manager
onToRight: if(view.currentIndex + 1 != view.count) view.currentIndex += 1
onToLeft: if(view.currentIndex != 0) view.currentIndex -= 1
}
PageIndicator {
id: indicator
count: view.count
currentIndex: view.currentIndex
anchors.bottom: view.bottom
anchors.horizontalCenter: parent.horizontalCenter
}
}
The complete example can be found in the following link.
I'm trying to get user input from qml TextField to c++, but it only works if text property value is hardcoded (const value).
c++
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *rootObject = engine.rootObjects().first();
QObject *serverField1 = rootObject->findChild<QObject*>("serverField1");
qDebug() << serverField1->property("text"); //Here I expect to get user input
Qml
ApplicationWindow {
id: applicationWindow
visible: true
width: 300
height: 550
TextField {
id: serverField1
objectName: "serverField1"
width: 200
height: 110
// text: "hardcoded value" //If text is const value, qDebug will get data from this property
}
}
You are asking for the text of the TextField when the window is displayed so what you will get is the text you have initially set, what you should do is get it every time it changes. I think that you have some class that will handle some processing with that data, that class will be called Backend, it must inherit from QObject so that it can have a qproperty and embed an object of that class to QML through setContextProperty, so every time it changes the text in QML will also change the text in the Backend class object.
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlProperty>
#include <QDebug>
class Backend: public QObject{
Q_OBJECT
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
QString text() const{
return mText;
}
void setText(const QString &text){
if(text == mText)
return;
mText = text;
emit textChanged(mText);
}
signals:
void textChanged(const QString & text);
private:
QString mText;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
Backend backend;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("backend", &backend);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
// test
QObject::connect(&backend, &Backend::textChanged, [](const QString & text){
qDebug() << text;
});
return app.exec();
}
#include "main.moc"
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TextField {
id: serverField1
x: 15
y: 46
width: 120
height: 45
topPadding: 8
font.pointSize: 14
bottomPadding: 16
placeholderText: "Server Ip"
renderType: Text.QtRendering
onTextChanged: backend.text = text
}
}
You can find the complete code in the following link.
I have a custom QML item called "Cell.qml" which I'd like to insert dynamically in my root window and make it visible. I also tried changing the z property, but I couldn't fix it, the object is still invisible (even tough the output of root->dumpObjectTree() says the object exists as a child of the root window)
This is the result after executing the code
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QObject *root = engine.rootObjects()[0];
QQmlComponent component(&engine, "qrc:/Cell.qml");
if (component.isReady()){
QObject *object = component.create();
object->setParent(root);
engine.setObjectOwnership(object, engine.CppOwnership);
}
root->dumpObjectTree();
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")
}
Cell.qml
import QtQuick 2.0
import QtQuick.Controls 2.3
Item{
property string txt: ""
property color c: "#d4ccc4"
visible: true
z:20
Rectangle {
width: 75; height: 75
color: c
visible: true
radius : 3
scale : 1
z:10
Text{
anchors.centerIn: parent
text: txt
font.family: "Helvetica"
font.pointSize: 20
color: "white"
}
}
}
Output of root->dumpObjectTree();:
QQuickWindowQmlImpl::
QQuickRootItem::
Cell_QMLTYPE_0::
QQuickRectangle::
QQuickText::
setParent() sets a non-visual, QObject level parent member. QQuickItem has another property, parentItem which is the parent QQuickItem property in QML, it is that property that needs to be set so the object appears visually.
I'm just wondering if anything like this is possible :
Loader {
id: loader
objectName: "loader"
anchors.centerIn: parent
sourceComponent: cppWrapper.getCurrentDisplay();
}
And in C++ :
QDeclarativeComponent currentDisplay;
and
Q_INVOKABLE QDeclarativeComponent getCurrentDisplay() const
{ return currentDisplay; }
I have trouble compiling it (it fails in the moc file compilation), but if it's possible, it can be a real shortcut for me
Sure, you can create Component in C++ part (as QQmlComponent) and return it to QML part.
Simple example (I use Qt 5.4):
First of all I create a class to use it as singleton (just for ease using)
common.h
#include <QObject>
#include <QQmlComponent>
class Common : public QObject
{
Q_OBJECT
public:
explicit Common(QObject *parent = 0);
~Common();
Q_INVOKABLE QQmlComponent *getComponent(QObject *parent);
};
common.cpp
QQmlComponent *Common::getComponent(QObject *parent) {
QQmlEngine *engine = qmlEngine(parent);
if(engine) {
QQmlComponent *component = new QQmlComponent(engine, QUrl("qrc:/Test.qml"));
return component;
}
return NULL;
}
Now I create and register my singleton:
main.cpp
#include "common.h"
static QObject *qobject_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
static Common *common = new Common();
return common;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
qmlRegisterSingletonType<Common>("Test", 1, 0, "Common", qobject_singletontype_provider);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Ok, now we have a singleton and it is very simple to use it in QML:
main.qml
import QtQuick 2.3
import Test 1.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
id: mainWindow
Loader {
id: loader
objectName: "loader"
anchors.centerIn: parent
sourceComponent: Common.getComponent(mainWindow)
}
}
Also our component we created in C++:
Test.qml
import QtQuick 2.3
Rectangle {
width: 100
height: 100
color: "green"
border.color: "yellow"
border.width: 3
radius: 10
}
Pay attention: all our QML files are in resource but it's just for example and you can put it in any place you want in your case
I'm having some difficuly calling a method from a C++ class in QML. I keep getting a "Cannot call method 'x' of null" error. Here is my code:
QML:
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import Jane 1.0
ApplicationWindow
{
property MainWindowModel m_Model
...
Button {
id: m_PluralizeButton
text: "Pluralize"
anchors.left: parent.left
anchors.leftMargin: 10
anchors.top: m_OutputRow.bottom
anchors.topMargin: 10
onClicked: m_OutputText.text = m_Model.getPluralization();
}
}
MainWindowModel.h
class MainWindowModel : public QObject
{
Q_OBJECT
public:
MainWindowModel();
~MainWindowModel() {}
Q_INVOKABLE QString getPluralization() const;
private:
};
MainWindoModel.cpp
MainWindowModel::MainWindowModel() :
QObject()
{
}
QString MainWindowModel::getPluralization() const
{
return "Test";
}
Main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Need to register types prior to loading the file.
qmlRegisterType<MainWindowModel>("Jane", 1, 0, "MainWindowModel");
QQmlApplicationEngine engine(QUrl("qrc:/root/QML/MainWindowView.qml"));
QObject* topLevel = engine.rootObjects().value(0);
QQuickWindow* win = qobject_cast<QQuickWindow*>(topLevel);
if (!win)
{
qWarning("Error: not a valid window.");
return -1;
}
win->show();
return a.exec();
}
Any help will be appreciated, thanks.
You need to create your MainWindowModel first.
QML:
import Jane 1.0
...
MainWindowModel {
id: m_Model;
}
Button {
...
onClicked: m_OutputText.text = m_Model.getPluralization();
}