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 debuggerV8Debugger - The V4 debuggerQmlInspector - The QML inspectorCanvasFrameRate - The QML profilerEngineControl - 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.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<