C++ で QQuickItem のメソッドを呼び出すことは可能ですか?
私の考えは、Qml で作成されたグラフィカル UI を使用してプログラムを作成することです。この 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() メソッドを呼び出す方法を教えてくれませんか?
よろしく