【问题标题】:QML/C++ Change Property During Run-timeQML/C++ 在运行时更改属性
【发布时间】:2014-01-29 13:03:57
【问题描述】:

我正在尝试设置我的程序以从 QML 的输入字段中获取数据,然后将该数据传递给 C++,这将用于进行属性更改。例如,如果用户在输入字段中键入红色,则包含输入字段的矩形应变为红色。数据在 C++ 中被接收,但矩形的属性没有改变。

这是我的代码。任何帮助表示赞赏。

main.qml

Rectangle{
id: textbox
radius: 15.0
height: 300
width: 300
color: "white"
border.color: "lightblue"
border.width: 5
signal qmlSignal(string msg)
property alias textColor: colorText.color

TextInput
{
    id: inputText
    anchors.horizontalCenter: textbox.horizontalCenter
    anchors.verticalCenter: textbox.verticalCenter
    anchors.bottomMargin: 25
    color : "black"
    text : "type something..."
    font.pointSize: 20
    maximumLength: 17
    inputMethodHints: Qt.ImhNoPredictiveText
    selectByMouse: true

    onAccepted: { inputText.focus = false; 
        Qt.inputMethod.hide(); 
        textbox.qmlSignal(inputText.text); 
        console.log(colorText.color) }

 }
}

main.cpp

#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QtQuick>
#include <QObject>
#include <myclass.h>

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);

QtQuick2ApplicationViewer viewer;
viewer.setMainQmlFile(QStringLiteral("qml/Test3/main.qml"));

QObject *item = viewer.rootObject();

MyClass test;

QObject::connect(item, SIGNAL(qmlSignal(QString)), &test, SLOT(cppSlot(QString)));

viewer.showExpanded();

return app.exec();
}

myclass.h

#include<QObject>
#include<QDebug>
#include<QtQuick>
#include"qtquick2applicationviewer.h"

class MyClass: public QObject
{
Q_OBJECT

public:
MyClass();

public slots:
void cppSlot(const QString &msg)
{
    qDebug() << "Called the C++ slot with message:" << msg;
    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/Test3/main.qml"));

    QObject *item = viewer.rootObject();
    item->setProperty("color", "red");
}
};

【问题讨论】:

    标签: c++ qt properties qml


    【解决方案1】:

    为了解决您的问题,我相信您需要查看有关使用绑定扩展 QML 的课程。具体参见第 3 章:添加属性绑定,因为这显示了如何使用 Q_PROPERTY 宏在 C++ 对象和 QML 之间创建绑定。

    事实上,我强烈建议您完成 Qt Creator 的 Qt 安装随附的所有 QML 章节。教程章节可以通过欢迎页面访问

    1. 选择示例
    2. 在搜索中输入“章节
    3. 应列出六章

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多