PDA

View Full Version : QPushButton elide text



Cupidvogel
23rd May 2015, 14:32
I have a QPuhButton of fixed width. I want that whenever the text inside reaches the end with more text to follow, it should automatically add ellipsis, the way we can do in HTML content in web pages. I tried this:




tableWidget = new QTableWidget(1,2,this);
tableWidget->setGeometry(15,169,251,232);
tableWidget->setColumnWidth(0,198);
tableWidget->setColumnWidth(1,54);

QPushButton *textSnippet = new QPushButton();
textSnippet->setStyleSheet("text-align: left; border: none; padding-left: 10px;");
textSnippet->setCursor(Qt::PointingHandCursor);
QString qText = "Some text";
QFontMetrics metrics(textSnippet->font());
QString elidedText = metrics.elidedText(qText, Qt::ElideRight, textSnippet->width()-5);
textSnippet->setText(elidedText);

tableWidget->setCellWidget(0,1, textSnippet);


This does not work at all, the text continues until the very end and there is no ellipsis. Of course, I tried checking for a fixed number of characters (25), so that if the length of the text is beyond that, slice the first 25 characters and append an ellipsis and show it, but this results in a very non-uniform set of rows with ellipsis appearing at various positions in different rows.

How do I do it?

anda_skoa
23rd May 2015, 15:04
Are you passing an appropriate width value?
I.e. if you call metrics.width(qText), how many pixels does it need vs. what you are giving to elided text as available width?

Cheers,
_

Cupidvogel
23rd May 2015, 22:31
Do you mean to say that I should pass the width of the button (198 px here) explicitly instead of textSnippet->width()-5?

ChrisW67
23rd May 2015, 23:11
Since your textSnippet widget has not yet been displayed it is entirely possible it has no meaningful width of its own.

Cupidvogel
24th May 2015, 00:15
Hmm, makes sense. Will try to pass the width explicitly and let you guys know..

Added after 42 minutes:

Right. It totally works when I call the method after setting the width for the button. Pretty dumb of me to ask. :)