我正在尝试编写一些与 QML 对象交互的 Qt C++ 代码。目标是将在 TCP 套接字上接收到的字符串 append 到 GUI 上的文本日志中。每次收到新字符串时,我都会运行 appendText() 函数。我有一个当前工作的实现,它使用 QWidgets 和一个 .ui 文件。我需要一个相同的 QML 实现。我的 QWidget 实现使用 textBrowser 和 append 函数,如下所示。 “theString”随着程序的运行而变化,每个变化都会被 append ,填满文本日志。
//update the text log with data received on TCP socket
void MainWindow::appendText() {
ui->textBrowser->append(theString);
}
这给了我想要的结果,将每个字符串 append 到文本框中。输出应如下所示。
Control connection successful.
Data connection successful.
Control Packet Receieved:
1
Control Packet Receieved:
2
Control Packet Receieved:
3
Control Packet Receieved:
4
Control Packet Receieved:
1
Control Packet Receieved:
2
Control Packet Receieved:
3
Control Packet Receieved:
4
但是,当使用以下代码执行我认为与 QML 对象相同的功能时...
//update the text log with data received on TCP socket
void MainWindow::appendText() {
QMetaObject::invokeMethod(textbox, "append", Qt::DirectConnection, Q_ARG(QVariant, theString));
//QQmlProperty(textbox, "text").write(theString);
}
它只追加前两个字符串,除此之外不再追加。输出看起来像这样。
Control connection successful.
Data connection successful.
我已经广泛查看了有关在 C++ 中调用 QML 方法的文档,但仍然一无所获。任何帮助表示赞赏。感谢您的宝贵时间。
最佳答案
我无法重现您的问题。
可能的解决方案
使用import QtQuick.Controls 2.0
可能是一个解决方案。
在这种情况下,我会收到以下错误消息:
QMetaObject::invokeMethod: No such method QQuickTextArea::append(QVariant) Candidates are: append(QString)
根据错误消息的建议,您现在应该使用 QString
而不是 QVariant
作为参数类型:
QMetaObject::invokeMethod(textbox, "append", Qt::DirectConnection, Q_ARG(QString, theString));
更好的选择
正如 Qt 所提到的,你应该 avoid manipulating QML object from C++ (深入对象树):
Warning: While it is possible to use C++ to access and manipulate QML objects deep into the object tree, we recommend that you do not take this approach outside of application testing and prototyping. One strength of QML and C++ integration is the ability to implement the QML user interface separately from the C++ logic and dataset backend, and this strategy breaks if the C++ side reaches deep into the QML components to manipulate them directly.
因此,用 C++ 实现一个信号可能是一个更好的选择,它发出新收到的消息并从 QML 端连接到它。这种方法清楚地将用户界面和编程逻辑分开。
工作示例代码
以下代码每秒将 "test"
append 到 TextArea
。
主要.cpp:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QTimer>
#include <QQuickItem>
QObject *textbox;
void onTimeout()
{
QMetaObject::invokeMethod(textbox, "append", Qt::DirectConnection, Q_ARG(QVariant, "test"));
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QTimer t;
QObject::connect(&t, &QTimer::timeout, &onTimeout);
textbox = engine.rootObjects().first()->children().first();
t.start(1000);
return app.exec();
}
主.qml:
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 1.0
Window
{
visible: true
width: 600
height: 600
TextArea
{
id: textbox
anchors.fill: parent
}
}
关于c++ - 为什么我的 QML textArea 没有 append ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766735/