2016-12-05 82 views
0

我使用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状态红色图标正常。 (见下图)。你会看到如何改变我的代码,以便无论其状态如何,此按钮始终保持平坦?由于

off state on state

+0

如果您使用复选框单击其他位置以外的其他位置,它是否会正常显示?它看起来好像单元在试图点击其他地方时仍然有焦点 – Dusteh

+0

,即使失去焦点,按钮凸起的外观依然存在。 – Eurydice

回答

2

似乎与 “平” 物业相关的问题。 如果你能够改变图标的​​属性,可以使用下面的解决方案:使用

:中

// 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; 
+0

这是有效的!谢谢你的帮助 – Eurydice