前言
本文主要介绍的是使用代码生成的情况下对控件的介绍,包括拥有的功能及能修改的样式,也会说明在qtdesiner拖拽控件生成和使用代码生成控件的区别(如果有的话,遇到了的会说),此版本不属于最终版本,以后遇到什么新奇的点会继续更新!本文基于QT官方的文档进行的编写,QT版本为qt 5.14.0,编写环境为Windows11。不得不说官方文档真是个好东西,有时候有些不会的上去一看就能有灵感解决了,可惜没有中文版本的。
一、QStyledItemDelegate初步介绍
QStyledItemDelegate是 Qt 框架中用于模型视图架构的高级委托实现,它取代了旧的 QItemDelegate成为现代 Qt 应用中的首选委托类。这个类提供了更强大、更灵活的项渲染和编辑功能,同时与 Qt 的样式系统完美集成。
核心定位与优势
样式集成:完美支持 Qt 样式表(QSS)和 QStyle 系统
现代外观:自动适应不同平台和主题的视觉风格
数据类型支持:内置对常见 Qt 数据类型的渲染和编辑支持
扩展性:易于通过子类化进行自定义
最佳实践:Qt 官方推荐使用的委托基类
二、核心功能详解
1. 智能数据渲染
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
// 检查数据类型并自动选择合适的渲染方式
QVariant value = index.data(Qt::DisplayRole);
if (value.type() == QVariant::Icon) {
// 自动渲染图标
QIcon icon = qvariant_cast<QIcon>(value);
icon.paint(painter, option.rect, option.decorationAlignment);
}
else if (value.type() == QVariant::Color) {
// 自动渲染颜色块
QColor color = qvariant_cast<QColor>(value);
painter->fillRect(option.rect, color);
}
else {
// 默认文本渲染
QStyledItemDelegate::paint(painter, option, index);
}
}
2. 样式感知的编辑器
QWidget *createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
// 根据数据类型创建样式化编辑器
QVariant value = index.data(Qt::EditRole);
if (value.type() == QVariant::Date) {
QDateEdit *editor = new QDateEdit(parent);
editor->setCalendarPopup(true);
editor->setDisplayFormat("yyyy-MM-dd");
return editor;
}
else if (value.type() == QVariant::Bool) {
QCheckBox *editor = new QCheckBox(parent);
return editor;
}
// 默认创建基于当前样式的编辑器
return QStyledItemDelegate::createEditor(parent, option, index);
}
3. 样式表支持
/* 在样式表中自定义委托外观 */
QTableView {
alternate-background-color: #f0f0f0;
}
QTableView::item {
padding: 5px;
border: 1px solid transparent;
}
QTableView::item:selected {
background-color: #4a90e2;
color: white;
}
QTableView::item:hover {
background-color: #e6f2ff;
}
三、高级用法与技巧
1. 自定义特定列的渲染
class CustomStyledDelegate : public QStyledItemDelegate {
public:
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
// 为特定列使用自定义渲染
if (index.column() == 2) {
// 第三列
renderProgressBar(painter, option, index);
} else {
// 其他列使用默认渲染
QStyledItemDelegate::paint(painter, option, index);
}
}
private:
void renderProgressBar(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
// 获取


2051

被折叠的 条评论
为什么被折叠?



