0

我想让我QWidget在图像上显示光标的坐标,我读到最好的方法是使用QLineEdit,但我没有找到如何使用它。如何启动QLineEdit以及如何显示它,以便它跟随光标?PS:我知道如何在上面设置点坐标。这就是我的做法:

void QImageWidget::mouseMoveEvent( QMouseEvent *event ){
   int x = event->pos( ).x();
   int y = event->pos( ).y();
   if( cursorLineEdit != NULL && cursorLineEdit->isEnabled( ) )
       cursorLineEdit->setText( QString( "[ %1 , %2 ]" ).arg( x ).arg( y ) );
}

mouseTracking 已经设置为 true :

this->setMouseTracking(true);

谢谢 !

编辑: cursorLineEdit 是我要显示的 QLineEdit,我需要在我的 QWidget 构造函数上初始化它,但我不知道如何!

4

2 回答 2

2

You can do the following:

QImageWidget::QImageWidget()
{
    [..]
    cursorLineEdit = new QLineEdit(this);
    QVBoxLayout layout = new QVBoxLayout(this);
    layout->addWidget(cursorLineEdit);
    setMouseTracking(true);
    [..]
}

and

void QImageWidget::mouseMoveEvent( QMouseEvent *event )
{
   int x = event->pos().x();
   int y = event->pos().y();
   if (cursorLineEdit->isEnabled())
       cursorLineEdit->setText(QString( "[ %1 , %2 ]" ).arg( x ).arg( y ) );
}

EDIT:

An alternative way would be showing a tool tip with the coordinates:

void QImageWidget::mouseMoveEvent(QMouseEvent *event)
{
    const QPoint &p = event->pos();
    QToolTip::showText(mapToGlobal(p),
                       QString("[%1 , %2]").arg(p.x()).arg(p.y()), this,
                       QRect(p, QSize(20, 20)));
}
于 2014-08-20T12:41:22.863 回答
1

我找到了另一种解决方案,但首先我想告诉你,为什么我决定在这里发布我的答案。我认为我的解决方案效率不高而且非常负载 CPU,但是当我运行 vahancho 的代码时,我看到 QToolTip 也加载了 CPU(在我的计算机上,两种解决方案都可以将 CPU 从 0% 加载到 3%)所以现在我认为我可以在这里发布答案你可以决定你想使用什么。

思路:获取位置,创建透明像素图,在此像素图坐标上绘制,将此像素图设置为光标。此外,我们将使用一个 bool 变量(我们不会在每次 mouseMoveEvent 时都绘制像素图,我们将每隔一次绘制一次(为了提高效率))

bool showMustGoOn;//in header

showMustGoOn = false;//in constructor

void QImageWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(showMustGoOn)
    {
    const QPoint &p = event->pos();
    QPixmap px(50,10);
    px.fill(Qt::transparent);
    QPainter paint(&px);
    paint.drawText(10,10,QString("%1,%2").arg(p.x()).arg(p.y()));
    setCursor(QCursor(px));
    showMustGoOn = false;
    }
    else
    {
        showMustGoOn = true;
    }
}

如果你想使用它,你可以画另一个东西来显示光标。另一个优点是像素图是透明的,所以这个光标不会关闭另一个区域(你只看到数字,其他都是透明的,但工具提示关闭)

最后,在 Qwt 中也有类似的东西,我认为它更有效,但是在 Qwt 的源代码中搜索所需的代码可能会很长而且很复杂。

在此处输入图像描述

于 2014-08-20T17:24:53.600 回答