Search code examples
c++qtqlineeditqcursor

How to make a QLineEdit follow the cursor to show me its coordinates


I want my QWidget to show me the coordinates of my cursor when it's on the Image, I read that the best way is to use QLineEdit, but I didn't find how to use it to do so. How to initiate the QLineEdit and how to show it, in order that it follows the cursor ? PS : I know how to set the points coordinates on it. this is how i'm doing it :

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 ) );
}

the mouseTracking is already set true :

this->setMouseTracking(true);

Thanks !

EDIT : cursorLineEdit is the QLineEdit i want to show, I need to initialize it on my QWidget Constructor, but i don't know how !


Solution

  • I find one more solution, but first of all I want to tell you, why I decide post my answer here. I thought that my solution not efficient and very loads CPU, but when I run vahancho's code I saw that QToolTip loads CPU too (on my computer both solutions can load CPU from 0 to 3 percent) So now I think that I can post here answer and you be able to decide what you want to use.

    Idea: get the position, create transparent pixmap, draw on this pixmap coordinates, set this pixmap as a cursor. Moreover, we will use one bool variable(we will not draw pixmap every mouseMoveEvent, we will draw it every second time (for efficiency))

    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;
        }
    }
    

    If you want use it, you can draw something another to show the cursor. One more advanteges is that pixmap is transparent, so this cursor not close another area(you see just numbers, all another is transparent, but toolTip close)

    Finally, in Qwt there is something similar and I think it more efficient, but searching of needed code in the source code of Qwt can be very long and complicate.

    enter image description here