❝使用QPainter画透明时钟,还可拖动。❞
QPixmap pixmap = QPixmap(width, height);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHints(QPainter::SmoothPixmapTransform, true);
painter.setPen(QPen(Qt::white, width * 0.035));
/* 改变绘图坐标点。 */
painter.translate(width / 2, height/2);
/* 画白色圆环 */
painter.drawEllipse(-(width - painter.pen().width()) / 2,
-(height -painter.pen().width())/ 2,
height - painter.pen().width(),
height - painter.pen().width());
int circleRadius = width * 0.025;
painter.rotate(-90);
/* 绘制60个圆点 */
for (int i = 0; i < 60; i++) {
QColor color("#90d5d5d5");
if (i % 5 == 0) {
color = Qt::black;
/* 画数字 */
painter.drawPixmap(width*0.55/2, -25, createOneNumberPixmap(i == 0 ? 12 : i/5, 50, -i*6 + 90));
}
painter.rotate(6);
}
QPixmap pixmap = QPixmap(radius, radius);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
if (isBorder)
painter.setPen(QPen(QColor("#333333"), 1));
else
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(color));
painter.drawEllipse(0, 0, radius, radius);
QPixmap pixmap = QPixmap(width, height);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(color));
/* 画头部圆 */
painter.drawEllipse(0, 0, height, height);
/* 画矩形 */
painter.drawRect(height/2, 0, width - height, height);
/* 画尾部圆 */
painter.drawEllipse(width - height, 0, height, height);
QPixmap pixmap = QPixmap(width, height);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(Qt::NoPen);
painter.setBrush(QBrush(color));
const QPointF points[4] = {
QPointF(0, height),
QPointF(0, 0),
QPointF(width, height * 0.25),
QPointF(width, height * 0.75)
};
/* 画梯形,从左下角顺时针绘制。 */
painter.drawPolygon(points, 4);
m_timerId = this->startTimer(1000, Qt::PreciseTimer);
this->updateTime();
void ClockView::updateTime()
{
QTime currentTime = QDateTime::currentDateTime().time();
m_hourAngle = -90 + 30 * currentTime.hour() + 30 * currentTime.minute()/60;
m_minuteAngle = -90 + 6 * currentTime.minute();
m_secondAngle = -90 + 6 * currentTime.second();
update();
}
在桌面状态下运行效果:
setWindowFlags(Qt::FramelessWindowHint |
Qt::X11BypassWindowManagerHint);
setAttribute(Qt::WA_TranslucentBackground);
QPoint m_startPoint;
void ClockView::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
/* 记录鼠标左键按下的初始状态。 */
m_startPoint = frameGeometry().topLeft() - event->globalPos();
}
}
void ClockView::mouseMoveEvent(QMouseEvent *event)
{
/* 移动窗口 */
this->move(event->globalPos() + m_startPoint);
}