
Originally Posted by
axeljaeger
Delegate is the way to go, it is more light weight than setItemWidget, however, setItemWidget is easier to use. I'd go for the delegate.
Thanks for your help! In the code below you can see how I'm testing my delegate right now. It works just like I want as I can place my text with painter wherever I want. Thanks!
My problem is now that from this blog http://labs.trolltech.com/blogs/2007...ng-item-views/ I have understood that my delegate should be able to use the QStyles that is set in the application. So what I do in my application is just to set the stylesheets for QListWidget::item and QListWidget::item:selected but nothing happens to my QListWidget::items that is created in the delegate. What am I doing wrong here? Should I do something else in my paint method to get Stylesheets working?
This is my code:
Code:
class MyDelegate : public QStyledItemDelegate {
public:
MyDelegate(QObject *parent=0) : QStyledItemDelegate (parent){}
void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const{
if(option.state & QStyle::State_Selected){
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
QString title = index.data(Qt::DisplayRole).toString();
QString description = index.data(Qt::UserRole + 1).toString();
r = option.rect.adjusted(50, 0, 0, -50);
painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom|Qt::AlignLeft|Qt::TextWordWrap, title, &r);
r = option.rect.adjusted(50, 50, 0, 0);
painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft|Qt::TextWordWrap, description, &r);
}
QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const{
return QSize(200, 100);
}
};
int main(int argc, char **argv){
QApplication app(argc, argv);
QListWidget listWidget;
app.setStyleSheet("QListWidget { background: red; } QListWidget::item { background: yellow; } QListWidget::item:selected { background: blue; }");
for (int i = 0; i < 4; i++) {
QListWidgetItem *item = new QListWidgetItem();
item->setData(Qt::DisplayRole, "This is the title");
item->setData(Qt::UserRole + 1, "This is description");
listWidget.addItem(item);
}
listWidget.setItemDelegate(new MyDelegate(&listWidget));
listWidget.showMaximized();
return app.exec();
}