Search code examples
qtstylinglines

Qt QListWidgetItem Multiple Lines


I have a really simple QListWidget object and I want to build a folder list. When I add an item to my list here is what I do :

void LessCC::on_addFolderButton_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(this, tr("Choose Directory"), QDir::homePath(), QFileDialog::ShowDirsOnly);
    QListWidgetItem* newItem = new QListWidgetItem(QIcon(":/resources/icons/folder.png"), dirName, 0, 0);
    this->ui->folderListWidget->addItem(newItem);
}

This is working but I want my items to have multiple lines or column of informations (with different style).

I heard about the QStyledItemDelegate but I don't really understand how it works because all other solutions I've found seems really complicated for such simple(?) thing.

Is this the only solution or maybe there is something much more simple I did not see ?

Hope someone can help me.


Solution

  • It's a little difficult to suggest the "best" solution without seeing exactly what you want your list item to look like, but we'll give it a try.

    There is actually a great post on the Qt thread here that finally at the end gives all the code they use to create a list sort of like the one they show at the top.

    Basically, each item has a large icon, and to the right there is a title and description text, each styled differently.

    Creating a custom delegate sounds scary, but it is basically just providing a custom widget for the list. It works essentially like a template. You define what you want your list item to look like, and you paint it using data from list. You just can inherit from QAbstractItemDelegate.

    #include <QPainter>
    #include <QAbstractItemDelegate>
    
    class ListDelegate : public QAbstractItemDelegate
    {
        public:
           ListDelegate(QObject *parent = 0);
    
           void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const;
           QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const;
    
           virtual ~ListDelegate();
    };
    

    The biggest job is to code the paint function. I'll just show the basics here, but you can reference the link above for a longer example.

    ListDelegate::ListDelegate(QObject *parent)
    : QAbstractItemDelegate(parent)
    {
    
    }
    
    void ListDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
    {
            QRect r = option.rect;
    
            QPen fontPen(QColor::fromRgb(51,51,51), 1, Qt::SolidLine);
    
            if(option.state & QStyle::State_Selected)
                {
                painter->setBrush(Qt::cyan);
                painter->drawRect(r);
    
            } 
                else 
                {
                //BACKGROUND ALTERNATING COLORS
                painter->setBrush( (index.row() % 2) ? Qt::white : QColor(252,252,252) );
                painter->drawRect(r);
            }
    
                painter->setPen(fontPen);
    
            //GET TITLE, DESCRIPTION AND ICON
            QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
            QString title = index.data(Qt::DisplayRole).toString();
            QString description = index.data(Qt::UserRole).toString();
    
            int imageSpace = 10;
            if (!ic.isNull()) 
                {
                //ICON
                r = option.rect.adjusted(5, 10, -10, -10);
                ic.paint(painter, r, Qt::AlignVCenter|Qt::AlignLeft);
                imageSpace = 55;
            }
    
            //TITLE
            r = option.rect.adjusted(imageSpace, 0, -10, -30);
            painter->setFont( QFont( "Lucida Grande", 6, QFont::Normal ) );
            painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom|Qt::AlignLeft, title, &r);
    
            //DESCRIPTION
            r = option.rect.adjusted(imageSpace, 30, -10, 0);
            painter->setFont( QFont( "Lucida Grande", 5, QFont::Normal ) );
            painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r);
    
    }
    
    QSize ListDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
    {
       return QSize(200, 60); // very dumb value
    }
    
    ListDelegate::~ListDelegate()
    {
    
    }
    

    So you can see in this code we are getting three bits of data from the list. The icon, the title, and the description. Then we are displaying drawing the icon, and drawing the two text strings how we like. But the important part is getting the data itself. We are basically asking the list to give us the data using the "index" that was passed to us.

    QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
    QString title = index.data(Qt::DisplayRole).toString();
    QString description = index.data(Qt::UserRole + 1).toString();
    

    You'll notice that each bit of information was retrieved using a different "role". Normally a list has only one thing it displays - which is accessed through the DisplayRole. Icons are stored in the DecorationRole. But if you want to store more stuff, then you start using UserRole. You can store a whole slew of things using UserRole, UserRole +1, UserRole +2 etc....

    So how you do you store all this information in each item. Easy...

    QListWidgetItem *item = new QListWidgetItem();
    item->setData(Qt::DisplayRole, "Title");
    item->setData(Qt::UserRole, "Description");
    myListWidget->addItem(item);
    

    And finally, how do you make the list display the item using your fancy new delegate?

    myListWidget->setItemDelegate(new ListDelegate(myListWidget));
    

    Hopefully that clarified things a little bit.