Text of QPushButton centered but left if text is to long
-
Hello.
I want the texts of my QPushButton to be aligned centred. I know how to do that.
The texts of the buttons can change at runtime and it could be that the text are to long to be displayed entirely on the button. If this happens, the beginning and the end of the text are not displayed. In that case I want the text to be left aligned so that only the end of the text is cut off.
Is it possible to achieve this behaviour for QPushButton?
Thank you in advance
-
You need to subclass the button and implement a custom method for setting the text.
This should do what you want (assuming you have only buttons with text - without icons):
@
void MyButton::setAlignedText(const QString & text)
{
//set text
this->setText(text);//determine alignment QStyleOptionButton option; this->initStyleOption(&option); QRect textContentsRect = this->style()->subElementRect(QStyle::SE_PushButtonContents, &option, this); QFontMetrics fontMetrics(this->font()); if( fontMetrics.width(text) <= textContentsRect.width() ) //set centered aligned else //set left aligned
}
@