【问题标题】:Cannot draw checkbox in QStyledItemDelegate无法在 QStyledItemDelegate 中绘制复选框
【发布时间】:2013-03-05 22:20:14
【问题描述】:

我有一个QStyledItemDelegate 派生对象用于QTableView 派生视图。我根据模型索引数据类型进一步委托绘画和编辑器创建。对于bools,我想通过复选框来表示状态 - 但复选框从未出现。

这是基本的委托绘制函数:

void Sy_QtPropertyDelegate::paint( QPainter* painter,
                                   const QStyleOptionViewItem& option,
                                   const QModelIndex& index ) const
{
    painter->save();

    if ( index.column() == 0 ) {
        ...
    } else {
        QVariant var = index.data();
        bool modified = index.data( Sy_QtPropertyModel::ModifiedRole ).toBool();

        //  If the data type is one of our delegates, then push the work onto
        //  that.
        auto it = delegateMap_.find( var.type() );
        if ( it != delegateMap_.end() ) {
            ( *it )->paint( painter, option, index );
        } else if ( var.type() != QVariant::UserType ) {
            ...
        } else {
            ...
        }
    }

    painter->restore();
}

还有bool 子委托绘制函数:

void Sy_boolPD::paint( QPainter* painter,
                       const QStyleOptionViewItem& option,
                       const QModelIndex& index ) const
{
    painter->save();

    bool checked  = index.data().toBool();
    bool modified = index.data( Sy_QtPropertyModel::ModifiedRole ).toBool();

    QStyle* style = Sy_application::style();
    if ( modified ) {
        QStyleOptionViewItemV4 bgOpt( option );
        bgOpt.backgroundBrush = QBrush( Sy_QtPropertyDelegate::ModifiedColour );
        style->drawControl( QStyle::CE_ItemViewItem, &bgOpt, painter );
    }

    QStyleOption butOpt( option );
    butOpt.state = QStyle::State_Enabled;
    butOpt.state |= checked ? QStyle::State_On : QStyle::State_Off;
    style->drawControl( QStyle::CE_CheckBox, &butOpt, painter );

    painter->restore();
}

如果我强制 modified 为真,则背景是表格的颜色被适当更改,couting butOptrectstate 成员显示它们是正确的 - 但没有显示复选框!将QStyle::CE_CheckBox 设置为任何其他类型也不会导致任何渲染。

我经常使用 Qt 的 MVC 框架,但在这里我看不出哪里出错了。

【问题讨论】:

    标签: c++ qt model-view-controller


    【解决方案1】:

    我所要做的就是查看源代码...

    case CE_CheckBox:
        if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(option)) {
        ...
        }
    

    我传递给该方法的QStyleOption 被强制转换为用于绘制控件的特定类型,CE_CheckBox 需要QStyleOptionButton,如果强制转换失败,则绘图操作会静默跳过。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多