1

How to get the starting position of text in the QLabel. Ex: enter image description here

How can i get the Left Top position of the text displayed in the QLabel(only) without overriding the paintEvent. I dont have permission to override paintEvent or use other widgets like QLineEdit I can get the Width/Height using fontmetrics but to get X,Y for the text?

Wagmare
  • 1,354
  • 1
  • 24
  • 58
  • 1
    As presented this looks like an xy-problem (no pun intended). Can I ask why you want the coords of the top left corner of the text? How do you plan to use it? – G.M. Feb 11 '21 at 11:17
  • Thanks @G.M. , my intention is to draw a external widget of the size of the painted text and place it on top of the label where text aligned . – Wagmare Feb 11 '21 at 15:30

1 Answers1

2

you can use below code :

QFontMetrics fm(ui->label->font());
int textWide = fm.horizontalAdvance(ui->label->text());
int textHeight = fm.height();
int textX , textY;
if ((ui->label->alignment() & Qt::AlignLeft) == Qt::AlignLeft)
    textX = ui->label->x();
if ((ui->label->alignment() & Qt::AlignHCenter) == Qt::AlignHCenter)
    textX = ui->label->x() + ( ui->label->width() - textWide) / 2;
if ((ui->label->alignment() & Qt::AlignRight) == Qt::AlignRight)
    textX = ui->label->x() + ui->label->width() - textWide ;

if ((ui->label->alignment() & Qt::AlignTop) == Qt::AlignTop)
    textY = ui->label->y();
if ((ui->label->alignment() & Qt::AlignVCenter) == Qt::AlignVCenter)
    textY = ui->label->y() + ( ui->label->height() - textHeight) / 2;
if ((ui->label->alignment() & Qt::AlignBottom) == Qt::AlignBottom)
    textY = ui->label->y() + ui->label->height() - textHeight;

qDebug() << textX << textY << ui->label->x() << ui->label->y();
SajadBlog
  • 514
  • 2
  • 12