qml学习(一) window和rectangle的区别 与c++文件中信号槽的使用

一。qml中用Window方式:

QT       += qml quick

qml.qml:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 200
    height: 200
    Text {
        id: text
        anchors.centerIn: parent
        text: qsTr("hello world")
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }
}

main.cpp:

#include <QApplication>

#include <QQmlEngine>
#include <QQmlComponent>
#include <QObject>
#include <QQuickWindow>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QQmlEngine *engine = new QQmlEngine();
    QQmlComponent *component = new QQmlComponent(engine);
    component->loadUrl(QUrl(QStringLiteral("qrc:/helloworld.qml")));

    if(!component->isReady()) {
        qWarning("debug %s", qPrintable(component->errorString()));
        return -1;
    }

    QObject::connect(engine, SIGNAL(quit()), &a, SLOT(quit()));

    QObject *object = component->create();
    QQuickWindow *window = qobject_cast<QQuickWindow*>(object);
    window->show();

    return a.exec();
}

二。qml中用Rectangle方式:

QT       += qml quick

qml.qml:

import QtQuick 2.0
import QtQuick.Controls 2.0

Rectangle {
    width: 320
    height: 240

    MouseArea{
        anchors.fill: parent
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onClicked: {
            if(mouse.button === Qt.RightButton) {
                Qt.quit()
            } else if( mouse.button === Qt.LeftButton) {
                color = Qt.rgba((mouse.x % 255) / 255.0, (mouse.y % 255) / 255.0, 0.6, 1.0)
            }
        }

        onDoubleClicked: {
            color = "gray"
        }
    }
}

main.cpp:

//#include "widget.h"

#include <QApplication>

#include <QQmlEngine>
#include <QQmlComponent>
#include <QObject>
#include <QQuickWindow>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QQuickView viewer;
    viewer.setResizeMode(QQuickView::SizeRootObjectToView);
    viewer.setSource(QUrl(QStringLiteral("qrc:/helloworld.qml")));
    QObject::connect(viewer.engine(), SIGNAL(quit()), &a, SLOT(quit()));
    viewer.show();

    return a.exec();
}

注意区分main文件中的写法。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值