是否可以在C ++中调用QQuickItem的方法。
我的想法是使用Qml创建一个带有图形用户界面的程序。我想在这个UI上登录。现在我在其上放置了一个TextArea,并通过append()方法添加日志条目。使用此方法非常简单,但我不知道如何在C ++中执行此操作。这是我的计划的开始。我通过一个额外的“JavaScript”功能解决了这个程序,但我对此并不满意。
main.qml
import QtQuick 2.0
import QtQuick.Controls 1.0
Item {
id: root
width: 400
height: 400
signal requestMessage()
function addLine() {
log.append(addField.text.toString())
addField.text = ""
}
function cMessage(msg) {
log.append(msg)
}
TextArea {
id: log
x: 20
y: 28
objectName: "log"
width: 340
height: 200
anchors.right: parent.right
anchors.rightMargin: 20
anchors.left: parent.left
anchors.leftMargin: 20
}
TextField {
id: addField
x: 20
y: 252
height: 25
anchors.right: addButton.left
anchors.rightMargin: 10
anchors.left: parent.left
anchors.leftMargin: 20
}
Button {
id: addButton
x: 284
y: 252
width: 96
height: 27
text: "Hinzufügen"
anchors.right: parent.right
anchors.rightMargin: 20
MouseArea {
anchors.fill: parent
onClicked: addLine()
}
}
Button {
id: bindingButton
x: 239
y: 290
text: "Nachricht von C++"
anchors.right: parent.right
anchors.rightMargin: 20
MouseArea {
anchors.fill: parent
onClicked: requestMessage()
}
}
}
的main.cpp
#include <QGuiApplication>
#include <qtquick2applicationviewer.h>
#include <QQuickItem>
#include <QObject>
#include "myclass.h"
int main(int argc, char *argv[])
{
QGuiApplication a(argc, argv);
QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Bindings/main.qml"));
QQuickItem *item = viewer.rootObject();
MyClass myClass;
myClass.setViewer(&viewer);
QObject::connect(item, SIGNAL(requestMessage()), &myClass, SLOT(treatMessage()));
viewer.show();
return a.exec();
}
最后是myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H
#include <QObject>
#include <QQuickItem>
#include <qtquick2applicationviewer.h>
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0);
void setViewer(QtQuick2ApplicationViewer *newViewer) {
this->viewer = newViewer;
}
signals:
public slots:
void treatMessage() {
QQuickItem *root = viewer->rootObject();
QVariant message = "hello from the other side";
QMetaObject::invokeMethod(root, "cMessage", Q_ARG(QVariant, message));
}
protected:
QtQuick2ApplicationViewer * viewer = 0;
};
#endif // MYCLASS_H
那么有人知道一种更优雅地完成这项任务的方法吗?或者有人能告诉我如何调用append()方法吗?
此致
答案 0 :(得分:2)
你绝对可以从QML方面调用QML项目上的方法。请参阅此处的文档:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.htmls
你已经掌握了大部分内容,你只需要找到你真正的TextArea:
findChild(QStringLiteral("log"))
上呼叫rootObject()
。请参阅:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.html#accessing-loaded-qml-objects-by-object-name QMetaObject::invokeMethod
来调用append方法。请参阅:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.html#invoking-qml-methods