Qt在高分辨率屏幕上加载图片

1.图片资源关联设备缩放比
QPixmap Pixmg::getPixmap(const QString name, const QSize size)
{
const QIcon &icon = QIcon(name);
const qreal ratio = devicePixelRatioF();
QPixmap pixmap = icon.pixmap(size * ratio).scaled(size * ratio, Qt::KeepAspectRatio, Qt::SmoothTransformation);
pixmap.setDevicePixelRatio(ratio);
return pixmap;
}

2.绘制时钟
图片资源的宽,高
static const QSize clockSize = QSize(224, 224);
static const QSize pointSize = QSize(145, 15);

void Pixmg::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)

QPixmap pix;
QDateTime datetime(QDateTime::currentDateTimeUtc());
const QTime time(datetime.time());
QPainter painter(this);
painter.setRenderHints(QPainter::**HighQualityAntialiasing** | QPainter::SmoothPixmapTransform);

// draw plate
painter.save();
pix = getPixmap(":/images/clock_black.svg", clockSize);
painter.translate(width() / 2.0, height() / 2.0);
painter.drawPixmap(QPointF(-clockSize.width()/2, -clockSize.height()/2), pix);
painter.restore();

int nHour = (time.hour() >= 12) ? (time.hour() - 12) : time.hour();
int nStartAngle = 90;//The image from 0 start , but the clock need from -90 start

// draw hour hand
const qreal hourAngle = qreal(nHour * 30 + time.minute() * 30 / 60 + time.second() * 30 / 60 / 60 - nStartAngle);
painter.save();
painter.translate(width() / 2.0, height() / 2.0);
painter.rotate(hourAngle);
pix = getPixmap(":/images/hour.svg", pointSize);
painter.drawPixmap(QPointF(-pointSize.width()/2, -pointSize.height()/2), pix);
painter.restore();

// draw minute hand
const qreal minuteAngle = qreal(time.minute() * 6 + time.second() * 6 / 60 - nStartAngle);
painter.save();
painter.translate(width() / 2.0, height() / 2.0);
painter.rotate(minuteAngle);
pix = getPixmap(":/images/minute.svg", pointSize);
painter.drawPixmap(QPointF(-pointSize.width()/2, -pointSize.height()/2), pix);
painter.restore();

// draw second hand
const qreal secondAngle = qreal(time.second() * 6 - nStartAngle);
painter.save();
painter.translate(width() / 2.0, height() / 2.0);
painter.rotate(secondAngle);
pix = getPixmap(":/images/second.svg", pointSize);
painter.drawPixmap(QPointF(-pointSize.width()/2, -pointSize.height()/2), pix);
painter.restore();

painter.end();

}

3.定时器超时,重绘时钟
QTimer *m_timer;

//在构造函数中初始化定时器,没500ms刷新调用一次update(即调用一次paintEvent)
Pixmg::Pixmg(QWidget *parent)
: QWidget(parent)
{
m_timer = new QTimer(this);
m_timer->start(500);
connect(m_timer, &QTimer::timeout, this, &Pixmg::onNotifyTest);
this->setStyleSheet(“background : green”);
}

void Pixmg::onNotifyTest()
{
update();
}

你可能感兴趣的:(Qt,C++)