笔者为这个问题思索了不少时间,这个问题就是c++ qt里创建了一个QStandardItemModel设置了表格的表头,往表格填充数据时,数据的复选框左对齐,想要设置复选框居中对齐,不知道如何处理,这里给出代码与运行效果,未来出现同样的问题时,可以拿来参考
c++ qt里想要设置QTableView复选框居中对齐,不知道如何处理。
给出自己的亲测有效的方法,并附上代码效果。使用委托
函数定义:
#include
#include
class CenteredCheckBoxDelegate : public QStyledItemDelegate {
Q_OBJECT
public:
using QStyledItemDelegate::QStyledItemDelegate;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
};
函数实现
void CenteredCheckBoxDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
QStyleOptionButton checkBoxOption;
checkBoxOption.state |= QStyle::State_Enabled;
if (index.model()->data(index, Qt::CheckStateRole).toBool()) {
checkBoxOption.state |= QStyle::State_On;
}
else {
checkBoxOption.state |= QStyle::State_Off;
}
bool isSelected = option.state & QStyle::State_Selected;
bool hasFocus = option.state & QStyle::State_HasFocus;
if (isSelected || hasFocus) {
painter->fillRect(option.rect, QColor(240, 240, 240)); // 选中或有焦点时的颜色
}
else {
QColor backgroundColor;
if (index.row() % 2 == 0) {
backgroundColor = QColor(255, 255, 255); // 偶数行
}
else {
backgroundColor = QColor(244, 246, 248); // 奇数行
}
painter->fillRect(option.rect, backgroundColor); // 未选中或没有焦点时的颜色
}
QRect checkBoxRect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkBoxOption, option.widget);
checkBoxRect.moveCenter(option.rect.center());
painter->save();
painter->translate(checkBoxRect.center());
QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkBoxOption, painter, option.widget);
painter->restore();
}
bool CenteredCheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) {
if (event->type() == QEvent::MouseButtonRelease) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (option.rect.contains(mouseEvent->pos())) {
// 检查该项是否可选(可选性数据需要在模型的某个地方被设置)
bool isCheckable = model->data(index, Qt::UserRole).toBool(); // 假设你在Qt::UserRole存储了可选性
if (isCheckable) {
// 改变选中状态
bool checked = model->data(index, Qt::CheckStateRole).toBool();
model->setData(index, !checked, Qt::CheckStateRole);
return true;
}
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index); // 对于其他事件,保持默认处理
}
代码含义讲解:这段代码主要讲解了复选框居中对齐,以及复选框如果选中会变颜色的操作