Qt 4.8 (4.8.6) 有一个带有 5 个参数的 QPainter::drawPixmapFragments() 重载函数:
void drawPixmapFragments(const QRectF *targetRects, const QRectF *sourceRects, int fragmentCount,
const QPixmap &pixmap, PixmapFragmentHints hints = 0);
Qt 5 (5.4.1) 没有这样的功能,它只有一个(与 Qt 4.8 相同)有 4 个参数:
void drawPixmapFragments(const PixmapFragment *fragments, int fragmentCount,
const QPixmap &pixmap, PixmapFragmentHints hints = 0);
我搜索过wiki.qt.io
在 stackoverflow 和其他几个地方搜索过,但没有答案如何将它从 Qt 4.8 移植到 Qt 5。
怎么做?
UPD我已经从 Qt 4.8.6 源代码 ( qpainter.cpp
) 中实现,并简单地将其转换为将指向 QPainter 的指针作为第一个参数:
namespace oldqt
{
void drawPixmapFragments(QPainter *painter, const QRectF *targetRects, const QRectF *sourceRects, int fragmentCount,
const QPixmap &pixmap, QPainter::PixmapFragmentHints hints)
{
// Q_D(QPainter);
if (/* !d->engine || */ pixmap.isNull())
return;
#ifndef QT_NO_DEBUG
if (sourceRects) {
for (int i = 0; i < fragmentCount; ++i) {
QRectF sourceRect = sourceRects[i];
if (!(QRectF(pixmap.rect()).contains(sourceRect)))
qWarning("QPainter::drawPixmapFragments - the source rect is not contained by the pixmap's rectangle");
}
}
#endif
// if (d->engine->isExtended()) {
// d->extended->drawPixmapFragments(targetRects, sourceRects, fragmentCount, pixmap, hints);
// }
// else {
if (sourceRects) {
for (int i = 0; i < fragmentCount; ++i)
painter->drawPixmap(targetRects[i], pixmap, sourceRects[i]);
}
else {
QRectF sourceRect = pixmap.rect();
for (int i = 0; i < fragmentCount; ++i)
painter->drawPixmap(targetRects[i], pixmap, sourceRect);
}
// }
}
}
但是我注释掉了一些行。Q_D(QPainter)
以某种方式d
从d_func
,我该如何从中获取*painter
?还是不可能?可能有另一种解决方案吗?
UPD2我的旧代码示例:
class ButtonSelector:public QGraphicsObject
// ...
void ButtonSelector::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
//painter->drawPixmap(m_backGnd.rect(), m_backGnd);
QRectF rectSrc = QRectF(m_backGnd.rect());
QRectF rectTrg = boundingRect();
painter->drawPixmapFragments(&rectTrg,&rectSrc,1,m_backGnd, QPainter::OpaqueHint);
// I've change it to this call:
// oldqt::drawPixmapFragments(painter, &rectTrg, &rectSrc, 1, m_backGnd, QPainter::OpaqueHint);
// where oldqt::drawPixmapFragments is function from above
// ... some other code unrelated to the question
}
原则上,它工作正常。代码中有什么不正确的地方?
void drawPixmapFragments(QPainter *painter, const QRectF *targetRects, const QRectF *sourceRects, int fragmentCount,
const QPixmap &pixmap, QPainter::PixmapFragmentHints hints)
{
for (int i = 0; i < fragmentCount; ++i) {
QRectF sourceRect = (sourceRects) ? sourceRects[i] : pixmap.rect();
QPainter::PixmapFragment pixmapFragment =
QPainter::PixmapFragment::create(
targetRects[i].center(),
sourceRects[i],
targetRects[i].width() / sourceRect.width(),
targetRects[i].height() / sourceRect.height()
);
painter->drawPixmapFragments(&pixmapFragment, 1, pixmap, hints);
}
}