我目前正在尝试使用全屏窗口,其中包含一个显示QGraphicsScene的QGraphicsView。我尝试使用鼠标滚轮实现“放大”和“缩小”功能。
但是,似乎调用scale()方法总是以左上角为锚点缩放视图(即使我将ResizeAnchor
和TransformAnchor
设置为{{1} }。这很烦人,因为视图的中心点相对于场景应保持不变。
这是我的ViewportAnchor::AnchorViewCenter
函数:
main
类int main(int argc, char* argv[])
{
QApplication a(argc, argv);
Map::Scene* scene = new Map::Scene();
Map::View* view = new Map::View(scene);
scene->addRect(500, 500, 200, 200);
scene->setBackgroundBrush(QBrush(QColor("gray")));
view->setScene(scene);
view->showFullScreen();
return a.exec();
}
继承自Map::View
,而QGraphicsView
继承自Map::Scene
。 QGraphicsScene
是一个空类(除了Map::Scene
继承的方法之外,没有任何方法或成员)。
这是QGraphicsScene
的实现:
Map::View
奇怪的是,通过将// .h
namespace Map
{
class View : public QGraphicsView {
Q_OBJECT
public:
View(Scene* scene);
~View() = default;
private:
const int WHEEL_UNIT_PER_DEGREES = 8;
const int WHEEL_STEPS_PER_DEGREE = 15;
const double ZOOM_OUT_FACTOR = 0.9;
const double ZOOM_IN_FACTOR = 1.1;
QPoint mouseOrigin;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
};
}
// .cpp
namespace Map {
View::View(Scene* scene) : QGraphicsView(scene)
{
// Remove scrollbars from view
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// Disconnect the scrollbars to prevent interference on view's positioning
horizontalScrollBar()->disconnect();
verticalScrollBar()->disconnect();
setResizeAnchor(ViewportAnchor::AnchorViewCenter);
setTransformationAnchor(ViewportAnchor::AnchorViewCenter);
}
void View::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton) {
mouseOrigin = event->pos();
}
}
void View::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton) {
QPointF oldPoint = mapToScene(mouseOrigin);
QPointF newPoint = mapToScene(event->pos());
// Invert the mouse movement for translation
QPointF translation = -(oldPoint - newPoint);
translate(translation.x(), translation.y());
mouseOrigin = event->pos();
}
}
void View::wheelEvent(QWheelEvent * event) {
QPoint degrees = event->angleDelta() / WHEEL_UNIT_PER_DEGREES;
if (!degrees.isNull()) {
double steps = degrees.y() / WHEEL_STEPS_PER_DEGREE;
double scaleFactor = 1.0;
if (steps < 0) {
scaleFactor = std::abs(steps) * ZOOM_OUT_FACTOR;
}
else {
scaleFactor = std::abs(steps) * ZOOM_IN_FACTOR;
}
scale(scaleFactor, scaleFactor);
}
}
}
实例设置为Map::View
的中央小部件,缩放似乎可以正常工作。但是,我不想看到QMainWindow
的工具栏和状态栏,将其删除会使问题再次出现。
有人遇到过这种问题吗?如果是,您如何解决呢?
谢谢!