简体   繁体   中英

How do I retrieve text from QML's TextField from C++ code?

I'm trying to retrieve the user input text value typed in the TextField but QML can't find my object, when I type something, the following error paper on Qt Creator's application output

ReferenceError: foo is not defined

What am I missing? note: Any better way to do this is very welcome. I just started learning QML.

Here's the code:

main.cpp

int main(int argc, char *argv[])
{
    //qRegisterMetaType<NameUserInput>(NAMEOF(NameUserInput));
    //qRegisterMetaType<NameUserInput*>(NAMEOF(NameUserInput*));
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    NameUserInput nameUserInput;
    QQmlApplicationEngine engine;
    engine.rootContext()->setProperty("foo", //&nameUserInput);
                                     QVariant::fromValue(&nameUserInput));
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);
    return app.exec();
}

NameUserInput.h

class NameUserInput : public QObject
{
    Q_OBJECT
public:
    explicit NameUserInput(QObject *parent = nullptr);
    //NameUserInput(const NameUserInput &other);
    NameUserInput(const QString &text);
    ~NameUserInput() override = default;
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
    QString text() const;
    void setText(const QString &text);
signals:
    void textChanged(const QString &text);
private:
    QString mText;
};

Q_DECLARE_METATYPE(NameUserInput*)

main.qml

    import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.5
import QtQuick.Controls.Styles 1.4

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("This is my application title!")

    ColumnLayout
    {
        id: col1
        spacing: 2

        Rectangle
        {
            width: 100
            Layout.preferredWidth: 40
            Layout.preferredHeight: 40
            Layout.alignment: Qt.AlignLeft
            Text {
                font.pointSize: 20
                id: label1
                text: qsTr("Your name:")
            }
        }

        Rectangle
        {
            width: 320
            Layout.preferredWidth: 40
            Layout.preferredHeight: 40
            Layout.alignment: Qt.AlignLeft
            TextField {
                placeholderText: "this is the default text"
                font.pointSize: 20
                //text: "this is my text"
                id: textEdit1
                onTextChanged: foo.text = text
                background: Rectangle {
                    border.color: "blue"
                    border.width: 3
                    radius: 12
                }
            }
        }

        Rectangle
        {
            width: 100
            Layout.preferredWidth: 40
            Layout.preferredHeight: 40
            Layout.alignment: Qt.AlignLeft
            Button
            {
                text: "Hit me!"
                onClicked: console.log("user input:" + textEdit1.text)
            }
        }
    }
}

If you want to export a QObject then you should use setContextProperty() , not setProperty() . Also it is not necessary to use QVariant.

engine.rootContext()->("foo", &nameUserInput);

On the other hand it is not necessary to use Q_DECLARE_METATYPE, and it is good practice to put Q_PROPERTY in the private section:

#ifndef NAMEUSERINPUT_H
#define NAMEUSERINPUT_H

#include <QObject>

class NameUserInput : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
public:
    explicit NameUserInput(QObject *parent = nullptr);
    NameUserInput(const QString &text);
    ~NameUserInput() override = default;
    QString text() const;
    void setText(const QString &text);
signals:
    void textChanged(const QString &text);
private:
    QString mText;
};


#endif // NAMEUSERINPUT_H

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM