c++ - 如何从 C++ 代码中检索 QML 的 TextField 中的文本?

标签 c++ qt qml user-input

我正在尝试检索在 TextField 中键入的用户输入文本值。但是QML找不到我的对象,当我输入一些东西时,Qt Creator的应用程序输出出现以下错误文件

ReferenceError: foo is not defined


我错过了什么?注意:非常欢迎任何更好的方法来做到这一点。我刚开始学习 QML。
这是代码:
主.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();
}
名称用户输入.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)
            }
        }
    }
}

最佳答案

如果你想导出一个 QObject 那么你应该使用 setContextProperty() ,而不是 setProperty() .也没有必要使用 QVariant。

engine.rootContext()->setContextProperty("foo", &nameUserInput);
另一方面,不必使用 Q_DECLARE_METATYPE,最好将 Q_PROPERTY 放在私有(private)部分中:
#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

关于c++ - 如何从 C++ 代码中检索 QML 的 TextField 中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62564186/

相关文章:

c++ - 无法推导模板参数

c++ - 我如何使用 C++ AMP 并行化以下循环?

c++ - 在调用传递给模板函数的函数时调用指向成员函数的指针

c++ - 将 MIPS 代码移植到 x86_64 时的浮点差异

c++ - QStandardItemModel::findItems 不在 QModelIndex(row, col, QModel(row,col)) 中搜索

qt - 同时在两个窗口中显示相机

qt - 如何访问通过 Loader 加载的 qml 页面的公共(public)属性?

qt - 如何向 QGraphicsView 的前景添加圆弧

c++ - 在播放视频之前寻找一个位置

linux - 如何使用 QML 更改系统日期和时间(嵌入式 Linux)?