是否可以在 C++ 中调用 QQuickItem 的方法。
我的想法是用 Qml 创建一个带有图形用户界面的程序。我想在这个 UI 上有一个日志。现在我在上面放置了一个 TextArea 并通过 append() 方法添加日志条目。使用此方法非常简单,但我不知道如何在 C++ 中执行此操作。这是我的程序的开始。我做了一个解决方法,通过一个额外的“JavaScript”函数来解决这个程序,但我对此并不满意。
主.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()
}
}
}
主要.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() 方法?
问候
最佳答案
您绝对可以从事物的 QML 端调用 QML 项上的方法。请在此处查看文档:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.htmls
您已经准备好大部分内容,您只需要通过以下方式找到您的实际 TextArea:
- 将 TextArea 上的 objectName 属性设置为类似“log”的值。
- 在 QQuickView 的
rootObject()
上调用findChild(QStringLiteral("log"))
。请参阅:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.html#accessing-loaded-qml-objects-by-object-name - 一旦你有了对它的引用,你就可以在它上面使用
QMetaObject::invokeMethod
来调用追加方法。请参阅:http://qt-project.org/doc/qt-5.1/qtqml/qtqml-cppintegration-interactqmlfromcpp.html#invoking-qml-methods
关于c++ - 在C++中调用QQuickItem(TextArea)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619685/