简体   繁体   English

在QGraphicsView中更改光标

[英]Changing the cursor in a QGraphicsView

I'm trying to change the cursor of a QGraphicsView while the ScrollHandDrag is on, but it doesn't seem to work. 我正在尝试在ScrollHandDrag打开时更改QGraphicsView的光标,但它似乎不起作用。 I can change the cursor if I disable the ScrollHandDrag but not while it's active, I don't see what I could possibly be doing wrong... 我可以更改光标,如果我禁用ScrollHandDrag但不是在它处于活动状态时,我不会看到我可能做错了什么...

Bellow is a portion of code that reproduce the problem: Bellow是重现问题的代码的一部分:

QApplication app(argc, argv);
QGraphicsScene scene;
QRect rectangle(-8, -4, 100, 100);
QPen pen(Qt::blue, 1, Qt::SolidLine);
scene.addRect(rectangle, pen);
scene.setBackgroundBrush(Qt::white);
QGraphicsView vue(&scene);
vue.setFixedSize(250, 250);
//vue.setDragMode(QGraphicsView::ScrollHandDrag);
vue.setCursor(Qt::CrossCursor);
vue.show();

return app.exec();

QGraphicsView will automatically change the cursor while dragging, but you can easily fix this by reimplementing a few functions: QGraphicsView会在拖动时自动更改光标,但您可以通过重新实现一些功能轻松解决此问题:

class CoolView : public QGraphicsView
{
protected:
    void enterEvent(QEvent *event)
    {
        QGraphicsView::enterEvent(event);
        viewport()->setCursor(Qt::CrossCursor);
    }

    void mousePressEvent(QMouseEvent *event)
    {
        QGraphicsView::mousePressEvent(event);
        viewport()->setCursor(Qt::CrossCursor);
    }

    void mouseReleaseEvent(QMouseEvent *event)
    {
        QGraphicsView::mouseReleaseEvent(event);
        viewport()->setCursor(Qt::CrossCursor);
    }
};

From poking around in Qt's source code, it looks like they take control of that cursor when you enter drag mode and there's no way to stop them from trying. 从Qt的源代码中探索,当你进入拖动模式并且没有办法阻止它们尝试时,它们看起来就像控制了那个光标。

The only workaround that I'm aware of is to use QApplication::setOverrideCursor() and QApplication::restoreOverrideCursor() which will set the cursor globally. 我所知道的唯一解决方法是使用QApplication::setOverrideCursor()QApplication::restoreOverrideCursor()来全局设置游标。 Unfortunately this means you'd have to do a lot managing of when the mouse cursor enters/leaves your QGraphicsView in order to prevent your whole application from getting stuck with the same cursor everywhere. 不幸的是,这意味着您必须对鼠标光标何时进入/离开QGraphicsView进行大量管理,以防止整个应用程序无法在任何地方卡住相同的光标。

It's also worth noting that the cursor is set at the viewport level, so it would be slightly more appropriate to do vue.viewport()->setCursor(Qt::CrossCursor) 还值得注意的是,光标设置在视口级别,因此更适合做vue.viewport()->setCursor(Qt::CrossCursor)

Reference documentation: 参考文件:

QApplication::setOverrideCursor 的QApplication :: setOverrideCursor

QApplication::restoreOverrideCursor 的QApplication :: restoreOverrideCursor

QApplication::changeOverrideCursor 的QApplication :: changeOverrideCursor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM