【问题标题】:QTableView and QAbstractTableModel with customized checkbox buttons带有自定义复选框按钮的 QTableView 和 QAbstractTableModel
【发布时间】:2016-12-06 01:57:54
【问题描述】:

我正在使用 qt5 (5.5.1) 派生通过 QAbstractTableModel 填充的 QTableView 小部件,我希望某些列(例如第三列)包含 QCheckBox 小部件。我希望这些QCheckBox 小部件使用两个图标进行自定义:一个红色球体代表错误状态,一个绿色球体代表真实状态,而不是标准的QCheckBox 外观。到目前为止一切顺利,我可以使用具有以下实现的自定义委托来做到这一点:

MyDelegate.cpp

#include "mydelegate.h"
#include <QCheckBox>
#include <QPainter>
#include <QKeyEvent>

#include <QtDebug>
#include <QApplication>
#include <QStyleOptionViewItem>

MyDelegate::MyDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
   // The green sphere
    _icon.addPixmap(QPixmap(":/selected.png"), QIcon::Normal, QIcon::On);
   // The red sphere
    _icon.addPixmap(QPixmap(":/deselected.png"), QIcon::Normal, QIcon::Off);
}

void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() != 2)
        QStyledItemDelegate::paint(painter,option,index);
    else
    {
        bool value  = index.model()->data(index,Qt::UserRole).toBool();
        QStyleOptionButton buttonVis;
        buttonVis.rect = option.rect;
        buttonVis.iconSize = QSize(15,15);
        buttonVis.icon = _icon;
        buttonVis.features |= QStyleOptionButton::Flat;
        buttonVis.state |= QStyle::State_Enabled;
        buttonVis.state |= value ? QStyle::State_On : QStyle::State_Off;
        QApplication::style()->drawControl(QStyle::CE_PushButton,&buttonVis,painter);
    }
}

bool MyDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if(event->type() == QEvent::MouseButtonRelease)
    {
        bool value  = model->data(index,Qt::UserRole).toBool();
        model->setData(index, !value, Qt::UserRole);
    }
    return true;
}

不幸的是,当我单击其中一个复选框时,on 状态绿色图标显示为凸起的按钮。 off 状态红色图标正常。 (见下图)。您是否知道如何更改我的代码以使该按钮无论其状态如何始终保持平坦?谢谢

【问题讨论】:

  • 如果您单击带有复选框的单元格以外的其他位置,它是否开始正常显示?它在我看来好像细胞仍然有焦点
  • 当试图点击其他地方时,即使失去焦点,按钮凸起的外观仍然存在。

标签: c++ qt


【解决方案1】:

似乎是与“平面”属性相关的问题。 如果您能够更改图标属性,则可以使用以下解决方案:

用途:

// The green sphere
_icon.addPixmap(QPixmap(":/selected.png"), QIcon::Normal, QIcon::On);
// The red sphere
_icon.addPixmap(QPixmap(":/deselected.png"), QIcon::Disabled, QIcon::On);

代替:

// The green sphere
_icon.addPixmap(QPixmap(":/selected.png"), QIcon::Normal, QIcon::On);
// The red sphere
_icon.addPixmap(QPixmap(":/deselected.png"), QIcon::Normal, QIcon::Off);

并使用:

buttonVis.state |= value ? QStyle::State_Enabled : QStyle::State_None;

代替:

buttonVis.state |= QStyle::State_Enabled;
buttonVis.state |= value ? QStyle::State_On : QStyle::State_Off;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多