效果:
实现原理:
自定义委托类,重写以下函数:
createEditor()
updateEditorGeometry()
setModelData()
setEditorData()
还可以重写**paint()**函数,绘制进度条,按钮等。
委托类代码:
.h
#ifndef CUSTOMERQSTYLEDITEMDELEGATE_H
#define CUSTOMERQSTYLEDITEMDELEGATE_H
#include <QStyledItemDelegate>
class CustomerQStyledItemDelegate : public QStyledItemDelegate
{
public:
CustomerQStyledItemDelegate();
~CustomerQStyledItemDelegate(){
}
protected:
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const;
void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
};
#endif // CUSTOMERQSTYLEDITEMDELEGATE_H
.cpp
#include "CustomerQStyledItemDelegate.h"
#include <QProgressBar>
#include <QApplication>
#include <QComboBox>
#include "mTableModel.h"
#include "QDebug"
CustomerQStyledItemDelegate::CustomerQStyledItemDelegate()
{
}
void CustomerQStyledItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem viewOption(option);
initStyleOption(&viewOption, index);
if (option.state.testFlag(QStyle::State_HasFocus))
viewOption.state = viewOption.state ^ QStyle::State_HasFocus;
QStyledItemDelegate::paint(painter, viewOption, index);
if (index.column() == 2)
{
int nProgress = index.model()->data(index, Qt::UserRole).toInt();
int nLeft = 8;
int nTop = 8;
int nWidth = option.rect.width() - 2 * nLeft;
int nHeight = option.rect.height() - 2 * nTop;
// 设置进度条的风格
QStyleOptionProgressBar progressBarOption;
progressBarOption.initFrom(option.widget);
// 设置进度条显示的区域
progressBarOption.rect = QRect(option.rect.left() + nLeft, option.rect.top() + nTop, nWidth, nHeight);
// 设置最小值
progressBarOption