Implementation of QML Tutorial 2 - QML Components
Qt下的窗口应用程序
mian.cpp
#include <QApplication>
#include <QtQuick/QQuickView>
#include <QtQuick/QQuickItem>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:/qml/colorpicker.qml"));
view.show();
QObject *item = view.rootObject()->findChild<QObject*>("myRect");
if (item) {
item->setProperty("color", QColor(Qt::yellow));
}
return a.exec();
}
colorpicker.qml
import QtQuick 2.0
Item {
id: container
property alias cellColor: rectangle.color
signal clicked(color cellColor)
width: 40; height: 25
Rectangle {
id: rectangle
border.color: "white"
anchors.fill: parent
}
MouseArea {
anchors.fill: parent
onClicked: container.clicked(container.cellColor)
}
}
colorpicker.qml
import QtQuick 2.0
Rectangle {
id: page
width: 320; height: 480
color: "lightgray"
Text {
id: helloText
text: "Hello world!"
y: 30
anchors.horizontalCenter: page.horizontalCenter
font.pointSize: 24; font.bold: true
}
Grid {
id: colorPicker
x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
rows: 2; columns: 3; spacing: 3
Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
}
}
QMLSample.pro
#-------------------------------------------------
#
# Project created by QtCreator 2020-12-23T14:17:57
#
#-------------------------------------------------
QT += core gui qml quick
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QMLSample
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as 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 \
mainwindow.cpp
HEADERS += \
mainwindow.h
DISTFILES += \
main.qml
RESOURCES += \
resource.qrc
效果
CMake编译
https://gitee.com/beibeix/cmake-examples/tree/master/CMakeQMLComponent