我使用QT5(5.5.1)来导出QTableView
插件通过QAbstractTableModel
为此,我想一些列(例如第3个一个)填充至包含QCheckBox
小部件。我希望那些QCheckBox
小部件可以用两个图标进行定制:虚假状态的红色球体和真实状态的绿色球体,而不是标准的QCheckBox
外观。到目前为止好,我可以做到这一点使用自定义委托具有以下实现:QTableView中和QAbstractTableModel定制复选框按钮
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
状态红色图标正常。 (见下图)。你会看到如何改变我的代码,以便无论其状态如何,此按钮始终保持平坦?由于
如果您使用复选框单击其他位置以外的其他位置,它是否会正常显示?它看起来好像单元在试图点击其他地方时仍然有焦点 – Dusteh
,即使失去焦点,按钮凸起的外观依然存在。 – Eurydice