从qml获取用户输入到c++

3

我正在尝试从 qml TextField 中获取用户输入并传递给 c++,但只有在文本属性值为硬编码(常量值)时才有效。

c++

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

QObject *rootObject = engine.rootObjects().first();
QObject *serverField1 = rootObject->findChild<QObject*>("serverField1");

qDebug() << serverField1->property("text"); //Here I expect to get user input

Qml

ApplicationWindow {
    id: applicationWindow
    visible: true
    width: 300
    height: 550

    TextField {
        id: serverField1
        objectName: "serverField1"
        width: 200
        height: 110
//    text: "hardcoded value" //If text is const value, qDebug will get data from this property
    }
}

@eyllanesc,我需要获取这个TextField中人们写入的文本,但是当我尝试获取text属性时,我没有得到人们输入的内容,而是得到我在qml中首先编码的text属性。 - BrutalWizard
1个回答

4
你在窗口显示时请求TextField的文本,所以你将得到最初设置的文本,你应该在每次更改时获取它。我认为你有一个类来处理这些数据,那个类将被称为Backend,它必须从QObject继承,以便它可以拥有一个qproperty,并通过setContextProperty在QML中嵌入一个那个类的对象,所以每次更改文本时,QML中的文本也会更改Backend类中的对象。

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQmlProperty>

#include <QDebug>

class Backend: public QObject{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
    QString text() const{
        return mText;
    }
   void setText(const QString &text){
        if(text == mText)
            return;
        mText = text;
        emit textChanged(mText);
    }
signals:
    void textChanged(const QString & text);
private:
    QString mText;
};

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    Backend backend;

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("backend", &backend);
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    // test

    QObject::connect(&backend, &Backend::textChanged, [](const QString & text){
        qDebug() << text;
    });
    return app.exec();
}

#include "main.moc"

main.qml

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    TextField {
        id: serverField1
        x: 15
        y: 46
        width: 120
        height: 45
        topPadding: 8
        font.pointSize: 14
        bottomPadding: 16
        placeholderText: "Server Ip"
        renderType: Text.QtRendering
        onTextChanged: backend.text = text
    }
}

你可以在以下链接中找到完整的代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接