qml与c++的简单实例,Connections信号连接

qml与c++的简单实例,Connections信号连接_第1张图片

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 

class Widget : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(int _width READ returnW NOTIFY rectChanged)
    Q_PROPERTY(int _height READ returnH NOTIFY rectChanged)
public:
    Widget(QWidget *parent = 0);
    ~Widget();

    int returnW(){return _width = width();}
    int returnH(){return _height = height();}
    void resizeEvent(QResizeEvent *event);

signals:
    void rectChanged();

private:
    int _width, _height;
    QQuickWidget *qmlWidget;
};

#endif // WIDGET_H


Widget类源文件

#include "widget.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    qmlWidget = new QQuickWidget(this);
    qmlWidget->rootContext()->setContextProperty("View",this);
    qmlWidget->setSource(QUrl(QStringLiteral("qrc:/Connections.qml")));
    resize(640,450);
}

Widget::~Widget()
{
    if(qmlWidget != NULL)
    {
        delete qmlWidget;
        qmlWidget = NULL;
    }
}

void Widget::resizeEvent(QResizeEvent *event)
{
    emit rectChanged();
}


qml文件,记得要把qml文件放到资源文件里面去哦

import QtQuick 2.0
import QtQuick.Controls 1.4

Rectangle {
    width: View._width
    height: View._height
    color: "green"

    Text {
        id: text1
        text: qsTr("text one")
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: parent.top
        anchors.topMargin: 30
        color: "blue"
        font.pixelSize: 18
    }

    Text {
        id: text2
        text: qsTr("text two")
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: text1.bottom
        anchors.topMargin: 50;
        color: "yellow"
        font.pixelSize: 18
    }


    Button {
        id: btn
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.top: text2.bottom
        anchors.topMargin: 50
        text: "Change"
    }

    Connections {
        target: btn
        onClicked: {
            text1.color = Qt.rgba(Math.random(),Math.random(),Math.random(),1);
            text2.color = Qt.rgba(Math.random(),Math.random(),Math.random(),1);
        }

// //类似的如果想用Widget里面的信号如下:
//        target: View
//        onRectChanged: test
    }
}

 

 

你可能感兴趣的:(Qt,Quick)