PDA

View Full Version : Add buttons to delegate paint method



antoinem
27th September 2016, 15:48
Hello,
I am designing an interface with Qt and I would like to have a list of elements (alerts). From what I have seen, the way to go would be a QListWidget with QListWidgetItems. To design the UI, I have used a custom subclass of QAbstractItemDelegate and I have reimplemented the paint method. What I have for now is this:

12128

with the following code:

AlertListDelegate.cpp:



void AlertListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QRect r = option.rect;

QString title = index.data(Qt::DisplayRole).toString();
QString description = index.data(Qt::UserRole).toString();

int imageSpace = 10;

//TITLE
r = option.rect.adjusted(imageSpace, 0, -10, -30);
painter->setFont(QFont( "Lucida Grande", 12, 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", 10, QFont::Normal));
painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r);
}


mainwindow.cpp:



QListWidget* myListWidget = new QListWidget();
myListWidget->setItemDelegate(new AlertListDelegate(myListWidget));

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

QListWidgetItem *item2 = new QListWidgetItem();
item2->setData(Qt::DisplayRole, "Title2");
item2->setData(Qt::UserRole, "Description2");
myListWidget->addItem(item2);

QListWidgetItem *item3 = new QListWidgetItem();
item3->setData(Qt::DisplayRole, "Title3");
item3->setData(Qt::UserRole, "Description3");
myListWidget->addItem(item3);


Now comes my problem: I would like to add some actions buttons into the interface (pushButtons for each alert that you can click). However I don't really see how to achieve this from the documentation or various examples. Maybe the paint method is not the way to do this but then how can I do it?

Also, I would like to have more elements in my Alert model (like a date, a time or some more details) and it seems like there are no "right" Qt roles to do it. Should I create a custom role enum to do it? I have not seen much examples about this.
Thank you for your help!