0
votes

I'm adding a QListWidgetItems to a QListWidget. Is there any way to set the size of the QListWidgetItem according to it's content data?

QSize size(50, 20);
QListWidgetItem* newItem1 = new QListWidgetItem();
newItem1->setText("short text");
newItem1->setSizeHint(size);
listWidget->addItem(newItem1); //listWidget is previously created
QListWidgetItem* newItem2 = new QListWidgetItem();
newItem2->setText("this is a very long text");
newItem2->setSizeHint(size);
listWidget->addItem(newItem2);

Text of newItem1 is displayed without any problem. But the newItem2 text is not fully displayed. It only shows few characters and then "..." as text elide. How to show the complete text without the elide? I want to set the size according to the size of item's data without setting any constant numbers.

2

2 Answers

0
votes

I simply copy/pasted your code, removed setSizeHint() function call for both items and added some of mine. Here's working code:

QListWidgetItem* newItem1 = new QListWidgetItem();
newItem1->setText("short text");
ui->listWidget->addItem(newItem1); 
QListWidgetItem* newItem2 = new QListWidgetItem();
newItem2->setText("this is a very long text");
ui->listWidget->addItem(newItem2);
ui->listWidget->setFixedSize(ui->listWidget->sizeHintForColumn(0) + ui->listWidget->frameWidth() * 2,
                             ui->listWidget->sizeHintForRow(0) * ui->listWidget->count() + 2 * ui->listWidget->frameWidth());

enter image description here

As you can see, both items are fully displayed.

0
votes

Actually I have accidentally enabled uniformItemSizes for the QListWidget. When I disable that, QListWidgetItems were automatically resized according to it's content.