#include"colormaker.h"
#include <QTimerEvent>
#include <QDateTime>
class ColorMaker:public QObject
{
Q_OBJECT
//如果你要导出的类定义了想在QML中使用的枚举类型,可以使用Q_ENUMS宏将该枚举类型注册到
//元对象系统中,一旦注册枚举类型,在QML中就可以用${CLASS_NAME}.{ENUM_VALUE}的形式来访问了
//例如ColorMaker.LinearIncrease
Q_ENUMS(GenerateAlgorithm)
Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(QColor timeColor READ timeColor)
public:
ColorMaker(QObject *parent = 0);
~ColorMaker();
//GenerateAlgorithm枚举类型,支持一系列颜色生成算法
enum GenerateAlgorithm{
RandomRGB,
RandomRed,
RandomGreen,
RandomBlue,
LinearIncrease
};
QColor color() const;
void setColor(const QColor & color);
QColor timeColor() const;
//类的成员函数使用Q_INVOKABLE来修饰,就可以让该方法被元对象系统调用,这个宏必须放在返回类型前面
Q_INVOKABLE GenerateAlgorithm algorithm() const;
Q_INVOKABLE void setAlgorithm(GenerateAlgorithm algorithm);
//一旦你使用了Q_INVOKABLE将某个方法注册到元对象系统中,在QML中就可以用
//${Object}.${method}来访问了
signals:
//两个信号
void colorChanged(const QColor &color);
void currentTime(const QString &strTime);
public slots:
//两个槽函数
void start();
void stop();
protected:
void timerEvent(QTimeEvent *e);
private:
GenerateAlgorithm m_algorithm;
QColor m_currentColor;
int m_nColorTimer;
};
ColorMaker::ColorMaker(QObject *parent):QObject(parent)
,m_algorithm(RandomRGB)
,m_currentColor(Qt::black)
,m_nColorTimer(0)
{
qsrand(QDateTime::currentDateTime().toTime_t());
}
ColorMaker::~ColorMaker()
{
}
QColor ColorMaker::color() const
{
return m_currentColor;
}
void ColorMaker::setColor(const QColor &color)
{
m_currentColor = color;
emit colorChanged(m_currentColor);
}
QColor ColorMaker::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);
}
ColorMaker::GenerateAlgorithm ColorMaker::algorithm() const
{
return m_algorithm;
}
void ColorMaker::setAlgorithm(GenerateAlgorithm algorithm)
{
m_algorithm = algorithm;
}
void ColorMaker::start()
{
if(m_nColorTimer == 0)
{
m_nColorTimer = startTimer(1000);
}
}
void ColorMaker::stop()
{
if(m_nColorTimer > 0)
{
killTimer(m_nColorTimer);
m_nColorTimer = 0;
}
}
void ColorMaker::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 RandomGreen:
m_currentColor.setGreen(qrand() % 255);
break;
case RandomBlue:
m_currentColor.setBlue(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 colorChanged(m_currentColor);
emit currentTime(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}
else
{
QObject::timerEvent(e);
}
}