qt : show mouse position like tooltip

♀尐吖头ヾ 提交于 2019-12-01 20:05:34

Assuming you want a coordinate readout as you move the cursor (like in many graphics or CAD applications), you really do not want to override QCursor.

The most efficient approach depends on what widget will be providing the coordinates, but in most cases the simplest way will be to setMouseTracking(true) for the widget, and override it's mouseMoveEvent(QMouseEvent* event) to display a QToolTip like so:

void MyWidget::mouseMoveEvent(QMouseEvent* event)
{
    QToolTip::showText(event->globalPos(),
                       //  In most scenarios you will have to change these for
                       //  the coordinate system you are working in.
                       QString::number( event->pos().x() ) + ", " +
                       QString::number( event->pos().y() ),
                       this, rect() );
    QWidget::mouseMoveEvent(event);  // Or whatever the base class is.
}

Normally you would not 'force' a tooltip like this; you would use QWidget::setToolTip(const QString&) or capture tooltip events in QWidget::event(QEvent*). But normal QToolTips only appear after short delay, but you want them updated continuously.

I should state that I haven't tried this, but this is the way I would do it. Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!