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

2019-04-29 04:42发布

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?

2条回答
放我归山
2楼-- · 2019-04-29 05:21

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

查看更多
做自己的国王
3楼-- · 2019-04-29 05:24

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;
}
查看更多
登录 后发表回答