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 (ie, 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?


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 eg

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


我建议重新实现createEditor函数:

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;
}
链接地址: http://www.djcxy.com/p/78990.html

上一篇: NSLocalizableString和info.plist

下一篇: 如何在Qt项目视图中设置单个单元格的委托?