博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
QML从文件加载组件简单示例
阅读量:7021 次
发布时间:2019-06-28

本文共 8679 字,大约阅读时间需要 28 分钟。

QML从文件加载组件简单示例

 

文件目录列表:

 

Project1.pro

QT += quickCONFIG += c++11CONFIG += declarative_debugCONFIG += qml_debug# The following define makes your compiler emit warnings if you use# any feature of Qt which as been marked deprecated (the exact warnings# depend on your compiler). Please consult the documentation of the# deprecated API in order to know how to port your code away from it.DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.# In order to do so, uncomment the following line.# You can also select to disable deprecated APIs only up to a certain version of Qt.#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0SOURCES += main.cppRESOURCES += qml.qrc# Additional import path used to resolve QML modules in Qt Creator's code modelQML_IMPORT_PATH =# Additional import path used to resolve QML modules just for Qt Quick DesignerQML_DESIGNER_IMPORT_PATH =# Default rules for deployment.qnx: target.path = /tmp/$${TARGET}/binelse: unix:!android: target.path = /opt/$${TARGET}/bin!isEmpty(target.path): INSTALLS += target

 

main.cpp

#include 
#include
int main(int argc, char *argv[]){ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec();}

 

ColorPicker.qml

import QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.3Rectangle {    id: colorPicker;    width: 50;    height: 30;    signal colorPicked(color clr);    function configureBorder()    {        colorPicker.border.width = colorPicker.focus ? 2 : 0;        colorPicker.border.color = colorPicker.focus ? "#90D750" : "#808080";    }    MouseArea {        anchors.fill: parent;        onClicked: {            colorPicker.colorPicked(colorPicker.color);            mouse.accepted = true;            colorPicker.focus = true;        }    }    Keys.onReturnPressed: {        colorPicker.colorPicked(colorPicker.color);        event.accepted = true;    }    Keys.onSpacePressed: {        colorPicker.colorPicked(colorPicker.color);        event.accepted = true;    }    onFocusChanged: {        configureBorder();    }    Component.onCompleted: {        configureBorder();    }}

 

main.qml

import QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.3ApplicationWindow {    visible: true;    width: 640;    height: 480;    title: qsTr("This is My Test");    MainForm {        anchors.fill: parent;    }}

 

MainForm.qml

import QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.3Rectangle {    id: mainForm;    width: 640;    height: 480;    color: "#EEEEEE";    Text {        id: coloredText;        anchors.horizontalCenter: parent.horizontalCenter;        anchors.top: parent.top;        anchors.topMargin: 4;        text: "Hello World";        font.pixelSize: 32;    }    Loader {        id: redLoader;        width: 80;        height: 60;        focus: true;        anchors.left: parent.left;        anchors.leftMargin: 4;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 4;        source: "ColorPicker.qml";        KeyNavigation.right: blueLoader;        KeyNavigation.tab: blueLoader;        onLoaded: {            item.color = "red";            // 获得初始焦点            item.focus = true;        }        onFocusChanged: {            // 更新focus状态, 以便触发 ColorPicker 的 onFocusChanged 信号            item.focus = focus;        }    }    Loader {        id: blueLoader;        focus: false;        anchors.left: redLoader.right;        anchors.leftMargin: 4;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 4;        source: "ColorPicker.qml";        KeyNavigation.left: redLoader;        KeyNavigation.tab: redLoader;        onLoaded: {            item.color = "blue";        }        onFocusChanged: {            // 更新focus状态, 以便触发 ColorPicker 的 onFocusChanged 信号            item.focus = focus;        }    }    Connections {        target: redLoader.item;        onColorPicked: {            coloredText.color = clr;            if ( !redLoader.focus ) {                redLoader.focus = true;                blueLoader.focus = false;            }        }    }    Connections {        target: blueLoader.item;        onColorPicked: {            coloredText.color = clr;            if ( !blueLoader.focus ) {                blueLoader.focus = true;                redLoader.focus = false;            }        }    }}

 

Ctrl + b  开始构建

Ctrl + r  运行

F5  开始调试

 

编译输出:

 

运行界面:

 

 

调试界面:

 

修改MainForm.qml文件,使之使用组件动态创建对象

import QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.3Rectangle {    id: mainForm;    width: 640;    height: 480;    property Component component: null;    property var dynamicObjects: new Array();    Text {        id: coloredText;        text: "Hello World";        anchors.centerIn: parent;        font.pixelSize: 24;    }    function changeTextColor(clr) {        coloredText.color = clr;    }    function createColorPicker(clr) {        if ( mainForm.component == null ) {            mainForm.component = Qt.createComponent("ColorPicker.qml");        }        // 局部变量        var colorPicker;        if ( mainForm.component.status == Component.Ready ) {            // 创建对象, 并设置一些初始属性值            colorPicker = mainForm.component.createObject(mainForm, {                                                            "color": clr,                                                              "x": mainForm.dynamicObjects.length * 55,                                                              "y": 10 });            // 设置处理colorPicked信号的槽函数为changeTextColor            colorPicker.colorPicked.connect(mainForm.changeTextColor);            mainForm.dynamicObjects[mainForm.dynamicObjects.length] = colorPicker;            console.log("add, mainForm.dynamicObjects.length = ", mainForm.dynamicObjects.length);        }    }    Button {        id: add;        text: "add";        anchors.left: parent.left;        anchors.leftMargin: 4;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 4;        onClicked: {            createColorPicker(Qt.rgba(Math.random()%255, Math.random()%255, Math.random()%255, 1));        }    }    Button {        id: del;        text: "del";        anchors.left: add.right;        anchors.leftMargin: 4;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 4;        onClicked: {            console.log("mainForm.dynamicObjects.length = ", mainForm.dynamicObjects.length);            if ( mainForm.dynamicObjects.length > 0 ) {                // 从数组中获取最后一个对象                var deleted = mainForm.dynamicObjects.splice(-1, 1);                // 删除最后一个对象                deleted[0].destroy();            }        }    }}

 

显示效果:

 

 

 

 

>>>>>>>>>>| 下面这种调试方法没有作用 |>>>>>>>>>>>>>>>

QML Debugging : 

The format is "-qmljsdebugger=[file:<file>|port:<port_from>][,<port_to>][,host:<ip address>][,block][,services:<service>][,<service>]*"

"file:" can be used to specify the name of a file the debugger will try to connect to using a QLocalSocket. If "file:" is given any "host:" and"port:" arguments will be ignored.
"host:" and "port:" can be used to specify an address and a single port or a range of ports the debugger will try to bind to with a QTcpServer.
"block" makes the debugger and some services wait for clients to be connected and ready before the first QML engine starts.
"services:" can be used to specify which debug services the debugger should load. Some debug services interact badly with others. The V4 debugger should not be loaded when using the QML profiler as it will force any V4 engines to use the JavaScript interpreter rather than the JIT. The following debug services are available by default:
QmlDebugger - The QML debugger
V8Debugger - The V4 debugger
QmlInspector - The QML inspector
CanvasFrameRate - The QML profiler
EngineControl - Allows the client to delay the starting and stopping of
             QML engines until other services are ready. QtCreator
             uses this service with the QML profiler in order to
             profile multiple QML engines at the same time.
DebugMessages - Sends qDebug() and similar messages over the QML debug
             connection. QtCreator uses this for showing debug
             messages in the debugger console.
Other services offered by qmltooling plugins that implement QQmlDebugServiceFactory and which can be found in the standard plugin paths will also be available and can be specified. If no "services" argument is given, all services found this way, including the default ones, are loaded.

 

 

 

 

 

 

 

 

 

 

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

 

转载地址:http://ymbxl.baihongyu.com/

你可能感兴趣的文章
Tomcat启动分析
查看>>
C++学习笔记(5):指针函数与函数指针
查看>>
Android 搭载Linux内核:三星放出源代码
查看>>
收藏链接地址,设为主页
查看>>
union union al l
查看>>
day-19:linux下打包tar工具及ZIP介绍
查看>>
lamp优化
查看>>
Bitshare2.0
查看>>
js实现继承方式
查看>>
单例模式 工厂模式
查看>>
使用Ext.grid.column.Column定义列
查看>>
程序员恶搞图片===爆笑中......娱乐一下.....
查看>>
关于WM_NCHITTEST消息(移动无标题对话框多个)
查看>>
配置管理小报100129:百兆和千兆网线
查看>>
Yii 2.0鉴权之RBAC(Yii2.0 Authorization By RBAC)
查看>>
理解矩阵
查看>>
Oracle~MyBatis~Java之Number长度对应的不同类型
查看>>
彻底理解ThreadLocal
查看>>
解决new org.jdom2.input.SAXBuilder报错
查看>>
对象导论
查看>>