QML / C ++在运行时更改属性

时间:2014-01-29 04:23:18

标签: c++ qt properties qml

我正在尝试设置我的程序从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");
}
};

1 个答案:

答案 0 :(得分:-1)

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

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

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