Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a delegate for a single cell in Qt item view?

Rather perplexed by this omission--but in Qt's QAbstractItemView class, it's possible to set a QAbstractItemDelegate (i.e., QItemDelegate or QStyledItemDelegate) to the entire view, a single row, or a single column, using the setItemDelegate* methods. In addition the item delegate for an individual cell can be queried, with QAbstractItemView::itemDelegate(const QModelIndex&), along with the delegate for rows, columns. and the entire view. But there appears to be no way to set an item delegate to an individual cell. Am I missing something? Any reason this should be?

like image 691
Matt Phillips Avatar asked Mar 15 '13 20:03

Matt Phillips


2 Answers

No you can't set item delegate only for one cell or one column but you can easly set item delegate for whole widget and choose in which cell, column or row you want to use your custom painting or something.

For e.g.

void WidgetDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                       const QModelIndex &index) const
{
    if (index.column() == 1) 
    {
        // ohh it's my column
        // better do something creative
    } 
    else // it's just a common column. Live it in default way
        QItemDelegate::paint(painter, option, index);
}

You can find some more information here

like image 78
Blood Avatar answered Oct 13 '22 04:10

Blood


I'd recommend reimplementing createEditor function instead:

QWidget * WidgetDelegate::createEditor(
        QWidget *parent,
        const QStyleOptionViewItem &,
        const QModelIndex &index) const
{
    QWidget *widget = 0;
    if (index.isValid() && index.column() < factories.size())
    {
        widget = factories[index.column()]->createEditor(index.data(Qt::EditRole).userType(), parent);
        if (widget)
            widget->setFocusPolicy(Qt::WheelFocus);
    }
    return widget;
}
like image 31
Jozef Doboš Avatar answered Oct 13 '22 05:10

Jozef Doboš