PDA

View Full Version : Make label follow qtextedit cursor



FabioG
22nd July 2020, 16:35
Hi all, I'm working on a shared editor and I need to make a label to follow a cursors position in the text.


- i tried with "ui->textEdit->viewport()->mapToGlobal(<textEdit cursor>);" -> it return me always the center of the window

- i tried to get the textEdit position and sum it to the position of the cursor as an offset -> but return the top left corner of the window

- i tried with "ui->textEdit->cursorRect() to get the actual cursor position -> but return the top left corner of the window

but nothing seems to work

13503

i want the label to align to that orange line I draw

right now I ended up with apply an offset I set manually but aparently it vary with the computer the application is running on

void MainWindow::UpdateCursorPosition(std::string user, int x, int y) {

QLabel *label;
if(usersCursors.find(user) != usersCursors.end()){
label = usersCursors.at(user);
// set label geometry to move it
label->setGeometry(x + 21, y + 40,/*label->sizeHint().width() +*/ 1, label->sizeHint().height() + 10);
}

}

d_stranz
22nd July 2020, 22:11
It sounds to me like you are confusing the mouse cursor with the QTextCursor. The QTextCursor position is defined as a character location within the QTextDocument, not the pixel location on screen in the QTextEdit widget.

FabioG
22nd July 2020, 23:10
I know they are different, but I was assuming there was also a way to know the pixel location of the text cursor.
So if there is no way to get the pixel position of the cursor how can I possibly achieve my goal?

FabioG
23rd July 2020, 08:14
https://doc.qt.io/qt-5/qtextedit.html#cursorRect-1 I supposed this was the function I was looking for but probably I misunderstood the "that includes the cursor of the text edit." part

FabioG
23rd July 2020, 14:36
I solved the problem

I used

"label->move(<point>)" instead of "setGeometry"

and I passed

"editor->mapTo(window(), editor->cursorRect(<cursor>).topLeft()" as point

so basically the point where the cursor is at the moment, remapped in the window coordinates