PDA

View Full Version : QLineEdit::cursorPositionAt(const QPoint) with Qt::AlignRight



JoZCaVaLLo
14th February 2012, 15:24
Hello!

when entering in a qlineedit I wish to set the cursor on the position where the click was done...

here is my code:



QPoint myPosition = this->mapFromGlobal(mouseClickPosition);
int txtCursorToSet = cursorPositionAt(myPosition );
setCursorPosition(txtCursorToSet);


This work only when the alignment() is Qt::AlignLeft... What should I do to get the same result with Qt::AlignHCenter and Qt::AlignRight?

JoZCaVaLLo
6th March 2012, 14:25
Well... I waited for a couple of weeks but no-one answered... :confused:

I found out a work-around... but maybe someone can provide better solutions! Or at least any documentation about that topic?



QPoint myPos = this->mapFromGlobal(mousePosition); // convert coordinates of the mouse click

if((alignment() &= Qt::AlignLeft) == Qt::AlignLeft) //when left alignment
{
int temp = cursorPositionAt(myPos); //use the easy way
setCursorPosition(temp);
return;
}
//cursorPositionAt works only for left or justified alignment,
//with other alignment it estimate always believing it is left alignment.
//deplacing the point of click is a workaround to this lack
QFontMetrics fm = fontMetrics();
int textWidth = fm.boundingRect(text()).width();

setCursorPosition(0); //set at 0 to get the cursorRect() at the right place

int marginWidth = cursorRect().right();
int rePosition = width();
if((alignment() &= Qt::AlignRight) == Qt::AlignRight)
{
rePosition = rePosition - textWidth + marginWidth;
}
else //center alignment
{
rePosition = rePosition / 2;
rePosition = rePosition - (textWidth / 2) + marginWidth;
}

myPos.setX(myPos.x() - rePosition);
int temp = cursorPositionAt(myPos);
setCursorPosition(temp);