QListWidget Add Custom Items in Qt?
Asked Answered
T

1

7

How to add 2 Images and Text in QListWidget at run time in Qt? I want to place one image at the beginning of the list and one at the end and text should be soon after my first Image.

itemclicked event

connect(list, SIGNAL(itemClicked()), this, SLOT(clicked(QListWidgetItem *)));
void MyWidget::clicked(QListWidgetItem *item)
{
   //code

}
Territus answered 8/11, 2011 at 8:41 Comment(0)
C
10

Have a look at the setItemWidget function. You can design a widget (call it MyListItemWidget) that contains two icon labels and a text label, and in its constructor provide the two icons and the text. Then you could add it to your QListWidget. Sample code follows:

QIcon icon1, icon2; // Load them 
MyListItemWidget *myListItem = new MyListItemWidget(icon1, icon2, "Text between icons");
QListWidgetItem *item = new QListWidgetItem();
ui->listWidget->addItem(item);
ui->listWidget->setItemWidget(item, myListItem );

You should also take a look at QListView and QItemDelegate which is the best option for designing and displaying custom list items.

EDIT CONCERNING YOUR CONNECTION

When connecting a signal to a slot their signature should match. This means that a slot cannot have more parameters than a signal. From the signals-slots documentation

The signals and slots mechanism is type safe: The signature of a signal must match the signature of the receiving slot. (In fact a slot may have a shorter signature than the signal it receives because it can ignore extra arguments.)

This means that your signal must have the QListWidgetItem * argument in the connection.

connect(list, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(clicked(QListWidgetItem *)))
Cheroot answered 8/11, 2011 at 9:1 Comment(5)
I followed the same approach as suggested by you that works fine but after that when i use itemclicked event on the list it gets fired on double click , it should work on single click.Territus
How do you handle the itemClicked signal? Some code would be helpfulCheroot
Sorry I am using the same signature for SIGNAL & SLOT Copy paste Error :(Territus
Have you debugged it? Are you sure that when a list item is clicked the slot is not called?Cheroot
Just to add to you example: Also add this line item->setSizeHint(QSize(0,65)); , Otherwise the added item will not be visible, as it happened when i tried using your example.Herren

© 2022 - 2024 — McMap. All rights reserved.