1

I've never done any item delegates in Qt before, and I think the documentation doesn't explain well about more complex delegates.

I need to create 2 styles of Symbian(^3) style lists

Type 1:

Delegate style 1

This is for common navigation lists, the icon and the lower label are optional.

Type 2:

Delegate style 2

This is for settings lists, where the pushbutton can be a toggle(on/off)-button or execute a context menu, etc.

How would I go on creating these sort of item delegates?

Best Regards, Rat

Gerstmann
  • 5,368
  • 6
  • 37
  • 57

2 Answers2

2

I had to make something similar once. This is how I did it.

My delegate class declaration. As you can see it has a member: QLabel *label. You can add another label or a pushbutton, depending on your needs.

class MyItemDelegate : public QStyledItemDelegate
{
public:
    explicit MyItemDelegate(QObject *parent = 0);
    ~MyItemDelegate();
protected:
    void paint(QPainter *painter,
               const QStyleOptionViewItem &option, const QModelIndex &index) const;
    QSize sizeHint(const QStyleOptionViewItem &option,
                   const QModelIndex &index) const;
private:
    QLabel *label;
};

My paint() and sizeHint() methods.

QSize MyItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(!index.isValid())
        return QSize();
    QVariant data = index.data(Qt::DisplayRole);

    label->setText(data.toString());
    label->resize(label->sizeHint());
    QSize size(option.rect.width(), label->height());
    return size;
}

void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if(!index.isValid())
        return;
    QVariant data = index.data(Qt::DisplayRole);

    // Not necessary to do it here, as it's been already done in sizeHint(), but anyway.
    label->setText(data.toString());

    painter->save();

    QRect rect = option.rect;

    // This will draw a label for you. You can draw a pushbutton the same way.
    label->render(painter, QPoint(rect.topLeft().x(), rect.center().y() - label->height() / 2),
                  QRegion(label->rect()), QWidget::RenderFlags());

    painter->restore();
}

Hope this is what you've been looking for. Good luck!

Yuliya
  • 220
  • 1
  • 4
0

You have 2 options ,

1) QML - This in my opinion is the best way to go and easier to achieve what you are trying to do. Link to Example

This shows you how to use a Delegate for a listview.

2)QItemDelegate - Subclass QItemDelegate then Assign a this delegate to a listview , Link to QItemDelegate

Abhijith
  • 2,592
  • 5
  • 18
  • 30
  • QML is not an option, as I want to maintain a native look and feel. I know I need to subclass QItemDelegate, the problem is that there is no documentation easy for me to comprehend regarding more complex delegates involving more than one type of ui element. – Gerstmann May 09 '11 at 04:56