How can I run commands on a Qt Quick TextEdit object from C++?

710 Views Asked by At

I am using a TextEdit object in Qt Quick via QML as such:

TextEdit {
    id: terminalText
    objectName: "terminalText"

    anchors.centerIn: parent
    font.family: "Courier New"
    Accessible.name: "document"
    baseUrl: "qrc:/"
    textFormat: Qt.PlainText

    width: parent.width - 30
    wrapMode: TextEdit.Wrap

    text: ""
}

I am trying to use C++ to directly interact with this object.

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

QObject *rootObject = engine.rootObjects().first();
terminal = rootObject->findChild<QObject*>("terminal");
QTextEdit *terminalText = (QTextEdit*)terminal->findChild<QObject*>("terminalText");
qDebug() << "terminalText: " << terminalText;
terminalText->append("test"); // Code crashes here

The output to log is:

terminalText:  QQuickTextEdit(0x7fce34c2b6a0, name = "terminalText")

which means that it is able to find the object in the UI. However, it seems that, despite casting the QObject pointer to a QTextEdit pointer, it considers itself a QQuickTextEdit.

I am unsure precisely what this means, but I am confused as to why the append() method, as shown here, causes the application to crash.

Having done some investigating, this initially seemed positive, however it seems to provide read-only access to a QQuickTextDocument, which also removes the possibility of utilising the QTextEdit methods. Also, I was unable to actually access this object:

QObject *terminalTextDocument = terminalText->document();
qDebug() << "terminalTextDocument: " << terminalTextDocument;

simply crashes as well.

What can I do to access the Qt Quick's TextEdit's append method?

1

There are 1 best solutions below

0
On BEST ANSWER

As you see yourself, the type of terminalText is QQuickTextEdit*, not QTextEdit*. You cannot cast between the two. That's all.

To call its methods from C++, you need to use QMetaObject::invokeMethod or QMetaMethod::invoke.

Alternatively, you use private Qt headers and use the proper C++ type:

#include <private/qquicktextedit_p.h>

...
auto terminalText = terminal->findChild<QQuickTextEdit*>("terminalText");
if (!terminalText) return;
terminalText->append("foo");