当您想要将较大的内容封装在较小的区域中并在其周围导航时,可以使用滚动区域或可滑动区域。就你而言,情况并非如此。您实际上并没有使用滚动区域,因为您的图像永远不会大于滚动区域的大小,您只是想伪造它,这实际上很简单:
#include <QQuickPaintedItem>
#include <QImage>
#include <QPainter>
class PImage : public QQuickPaintedItem {
Q_OBJECT
public:
PImage(QQuickItem * p = 0) : QQuickPaintedItem(p), xpos(0), ypos(0) {}
void paint(QPainter *painter) {
if (!source.isNull()) painter->drawImage(QRect(0, 0, width(), height()), source, QRect(xpos, ypos, width(), height()));
else painter->fillRect(QRect(0, 0, width(), height()), Qt::black);
}
public slots:
bool load(QString path) {
source = QImage(path);
return !source.isNull();
}
void moveBy(int x, int y) {
int ox, oy;
// don't go outside the image
ox = x + xpos + width() <= source.width() ? x + xpos : source.width() - width();
oy = y + ypos + height() <= source.height() ? y + ypos : source.height() - height();
if (ox < 0) ox = 0;
if (oy < 0) oy = 0;
if (ox != xpos || oy != ypos) {
xpos = ox;
ypos = oy;
update();
}
}
private:
QImage source;
int xpos, ypos;
};
在 QML 方面:
PImage {
width: 300
height: 300
Component.onCompleted: load("d:/img.jpg") // a big image
MouseArea {
property int ix
property int iy
anchors.fill: parent
onPressed: {
ix = mouseX
iy = mouseY
}
onPositionChanged: {
parent.moveBy(ix - mouseX, iy - mouseY)
ix = mouseX
iy = mouseY
}
}
}
这只是一个快速的基本示例,还有很多需要完善和改进的空间。另请注意,如果源矩形与目标矩形的大小不同,您可以轻松实现放大或缩小。您可以将其挂接到可轻拂的对象上以获得“动态滚动”而不是鼠标区域。