QML從文件加載組件簡單示例


QML從文件加載組件簡單示例

 

文件目錄列表:

 

Project1.pro

QT += quick
CONFIG += c++11
CONFIG += declarative_debug
CONFIG += 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.0

SOURCES += main.cpp

RESOURCES += qml.qrc

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

 

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>

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.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

Rectangle {
    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.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

ApplicationWindow {
    visible: true;
    width: 640;
    height: 480;
    title: qsTr("This is My Test");

    MainForm {
        anchors.fill: parent;
    }
}

 

MainForm.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

Rectangle {
    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.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

Rectangle {
    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.

 

 

 

 

 

 

 

 

 

 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM