建设对公银行网站打不开,赣州网站网站建设,茂名免费网站建设,WordPress自然志主题笔者为这个问题思索了不少时间#xff0c;这个问题就是c qt里创建了一个QStandardItemModel设置了表格的表头#xff0c;往表格填充数据时#xff0c;数据的复选框左对齐#xff0c;想要设置复选框居中对齐#xff0c;不知道如何处理#xff0c;这里给出代码与运行效果这个问题就是c qt里创建了一个QStandardItemModel设置了表格的表头往表格填充数据时数据的复选框左对齐想要设置复选框居中对齐不知道如何处理这里给出代码与运行效果未来出现同样的问题时可以拿来参考 文章目录 问题来源问题解决方案主要效果 问题来源
c qt里想要设置QTableView复选框居中对齐不知道如何处理。
问题解决方案
给出自己的亲测有效的方法并附上代码效果。使用委托 函数定义
#include QStyledItemDelegate
#include QPainterclass 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_castQMouseEvent*(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); // 对于其他事件保持默认处理
}
代码含义讲解这段代码主要讲解了复选框居中对齐以及复选框如果选中会变颜色的操作
主要效果