c++ - 无法在 QStyledItemDelegate 中绘制复选框

标签 c++ qt model-view-controller

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

这是基本委托(delegate)绘制函数:

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 子委托(delegate)绘制函数:

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 框架,但我看不出哪里出了问题。

最佳答案

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

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

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

关于c++ - 无法在 QStyledItemDelegate 中绘制复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15235273/

相关文章:

c++ - 为什么 std::less 比 "<"好?

c++ - 未为 QTableView 行调用 QStyledItemDelegate 的 sizeHint 方法

c++ - Q_INVOKABLE const getter 返回 undefined,non-const getter 返回正确值 - 为什么?

c++ - QComboBox 不显示其项目列表

c++ - 你为什么要将 10^9+7 加到一个数字上,然后用 10^9+7 求模

c++ - unique_ptr 麻烦吗? (与 2015 年相比)

c++ - 启动多个线程,只等待一个线程结束获取结果

javascript - 使用 SSL 运行的应用程序在第一次访问时未加载所有脚本/CSS

java - Spring mvc 3.1 tomcat 7 - 404 不解析 jsp 但 Controller 注释工作正常

ruby-on-rails - Rails 命名空间 Controller 问题