gpt4 book ai didi

c++ - 带有自定义复选框按钮的 QTableView 和 QAbstractTableModel

转载 作者:行者123 更新时间:2023-11-28 01:56:35 26 4
gpt4 key购买 nike

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

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

最佳答案

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

使用:

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

关于c++ - 带有自定义复选框按钮的 QTableView 和 QAbstractTableModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40976508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com