学习了 qt quick 的 c++ 跟 qml 混编,主要学习qml 如何调用 c++ 对象类型、响应 c++的槽函数。
//TestObj.h
#ifndef TESTOBJ_H
#define TESTOBJ_H
#include <QObject>
#include<QColor>
#include<QTime>
#include<QDateTime>
#include<QTimerEvent>
class TestObj : public QObject
{
Q_OBJECT
//qml要使用 c++ 枚举需要使用QENUMS来注册
Q_ENUMS(GenerateAlgorithm)
//Q_PROPERTY宏 可以 通过元对象系统访问属性,通过它定义的属性可以在qml中访问、修改;
//也可以在属性变化的时候发射特定信号。 使用该宏必须是 QOBJECT 后裔,和使用 Q_OBJECT 宏
/*
* Q_PROPERTY(type name *属性 名
(READ getFunction [WRITE setFunction *可选,声明一个设定属性的函数,他指定的属性,\
函数没有返回值,只能有一个与属性函数类型匹配的参数] |
MEMBER memberName [(READ getFunction | WRITE setFunction)])* READ 标记,\
MEMBER 标记 , 必须二选一 :声明一个读取属性的函数,该函数一般没有参数,返回它定义的属性
[RESET resetFunction]
[NOTIFY notifySignal] *可选配置,给属性关联一个信号(该信号必须在类中声明),当属性值发生变化就会
触发信号,信号的参数,一般就是定义的属性。
[REVISION int]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])
*/
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChange)
Q_PROPERTY(QColor timeColor READ timeColor)
public:
explicit TestObj(QObject *parent = nullptr);
~TestObj();
enum GenerateAlgorithm{
RandomRGB,
RandomRed,
RandomGreen,
RandomBlue,
LinearIncrease
};
//使用Q_INVOKABLE宏定义类成员函数,该方法就能被元对象系统使用
Q_INVOKABLE GenerateAlgorithm algorithm()const;
Q_INVOKABLE void setAlgorithm(GenerateAlgorithm algorithm);
QColor color()const;
void setColor(const QColor & color );
QColor timeColor()const;
protected:
void timerEvent(QTimerEvent * e);
private:
GenerateAlgorithm m_algorithm;
QColor m_currentColor;
int m_nColorTimer;
signals:
void colorChange(const QColor & color);
void currenTime(const QString & strTime);
public slots:
void start();
void stop();
};
#endif // TESTOBJ_H
TestObj.cpp
#include "testobj.h"
#include<QtDebug>
TestObj::TestObj(QObject *parent) : QObject(parent)
,m_algorithm(RandomRGB)
,m_currentColor(Qt::black)
,m_nColorTimer(0)
{
qsrand(QDateTime::currentDateTime().toTime_t());
}
TestObj::~TestObj()
{
}
TestObj::GenerateAlgorithm TestObj::algorithm() const
{
return m_algorithm;
}
void TestObj::setAlgorithm(TestObj::GenerateAlgorithm algorithm)
{
m_algorithm=algorithm;
}
QColor TestObj::color() const
{
return m_currentColor;
}
void TestObj::setColor(const QColor &color)
{
m_currentColor=color;
emit colorChange(m_currentColor);
}
QColor TestObj::timeColor() const
{
QTime time=QTime::currentTime();
int r=time.hour();
int g=time.minute()*2;
int b=time.second()*4;
return QColor::fromRgb(r,g,b);
}
void TestObj::timerEvent(QTimerEvent *e)
{
if(e->timerId()==m_nColorTimer){
switch (m_algorithm) {
case RandomRGB:m_currentColor.setRgb(qrand()%255,qrand()%255,qrand()%255);
break;
case RandomRed:m_currentColor.setRed(qrand()%255);
break;
case RandomBlue:m_currentColor.setBlue(qrand()%255);
break;
case RandomGreen:m_currentColor.setGreen(qrand()%255);
break;
case LinearIncrease:{
int r=m_currentColor.red()+10;
int g=m_currentColor.green()+10;
int b=m_currentColor.blue()+10;
m_currentColor.setRgb(r%255,g%255,b%255);
}
break;
}
emit colorChange(m_currentColor);
emit currenTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}else {
QObject::timerEvent(e);
}
}
void TestObj::start()
{
if(m_nColorTimer== 0 ){
m_nColorTimer=startTimer(1000);
}
}
void TestObj::stop()
{
if(m_nColorTimer>0){
killTimer(m_nColorTimer);
m_nColorTimer=0;
}
}
main.cpp
#include <QGuiApplication>
//#include <QQmlApplicationEngine>
#include<QtQuick/QQuickView>
#include<QtQml>
#include"testobj.h"
int main(int argc, char *argv[])
{
// QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
//注册qml可用类型 qmlRegisterSingletonType() 注册单例类型 qmlRegisterType()非单例
/* template<typename T>
int qmlRegisterType(const char *uri, int versionMajor, int versionMinor, const char *qmlName);
uri 包名 1 , 0 分别是版本versionMajor|versionMinor ,qmlname 是qml中要使用的类名。
*/
qmlRegisterType<TestObj>("he.TestObj.Color",1,0,"TestObj");
QQuickView viewer;
viewer.rootContext()->setContextProperty("rootv",&viewer);
viewer.setResizeMode(QQuickView::SizeRootObjectToView);
viewer.setSource(QUrl("qrc:///main.qml"));
viewer.show();
// QQmlApplicationEngine engine;
// const QUrl url(QStringLiteral("qrc:/main.qml"));
// QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
// &app, [url](QObject *obj, const QUrl &objUrl) {
// if (!obj && url == objUrl)
// QCoreApplication::exit(-1);
// }, Qt::QueuedConnection);
// engine.load(url);
return app.exec();
}
main.qml
import QtQuick 2.12
import QtQuick.Controls 2.0
//将c++类型导入
import he.TestObj.Color 1.0
Rectangle {
width: 360;
height: 360;
Text {
id: ttext;
anchors.left: parent.left;
anchors.leftMargin: 4;
anchors.top: parent.top;
anchors.topMargin: 4;
font.pixelSize: 32;
}
//c++对象
TestObj{
id:testObj;
color:Qt.green;
}
Rectangle{
id:colorRect;
anchors.centerIn: parent;
width: 150;
height: 150;
color: "blue";
}
Button{
id:start;
text: "Start";
anchors.left: parent.left;
anchors.leftMargin: 4;
anchors.bottom: parent.bottom;
anchors.bottomMargin: 4;
onClicked: {
//c++的槽函数响应
testObj.start();
}
}
Button{
id:stop;
text:"Stop";
anchors.left: start.right;
anchors.leftMargin: 4;
anchors.bottom: start.bottom;
onClicked: {
//c++的槽函数响应
testObj.stop();
}
}
function changeAlgorithm(button,algorithm){
switch(algorithm){
case 0:
button.text="RandomRGB";
break;
case 1:
button.text="RandomRed";
break;
case 2:
button.text="RandomBlue";
break;
case 3:
button.text="RandomGreen";
break;
case 4:
button.text="LinearIncrease";
break;
}
}
Button{
id:colorAlgorithm;
text: "RandomRGB";
anchors.left: stop.right;
anchors.leftMargin: 4;
anchors.bottom: start.bottom;
onClicked: {
//使用到了 Q_INVOKABLE宏 定义的两个函数
var algorithm=(testObj.algorithm()+1)%5;
changeAlgorithm(colorAlgorithm,algorithm);
testObj.setAlgorithm(algorithm);
}
}
Button{
id:quit;
text: "quit";
anchors.left: colorAlgorithm.right;
anchors.leftMargin: 4;
anchors.bottom: start.bottom;
//anchors.bottomMargin: 4;
onClicked: {
rootv.close();
}
}
Component.onCompleted: {
testObj.color=Qt.rgba(0,180,120,125);
testObj.setAlgorithm(testObj.LinearIncrease);
changeAlgorithm(colorAlgorithm,testObj.algorithm());
}
//响应testObj的 两个signal
Connections{
target: testObj;
onCurrenTime:{
ttext.text=strTime;
//Q_PROPERTY 宏定义函数 Q_PROPERTY(QColor timeColor READ timeColor)
ttext.color=testObj.timeColor;
}
}
Connections{
target: testObj;
onColorChange:{
//Q_PROPERTY 宏定义函数 Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChange)
colorRect.color=color;
}
}
// title: qsTr("Hello World")
}