qt自定义委托(进度条)

1.头文件

#include 

class Delegate : public QItemDelegate
{
    Q_OBJECT

public:
    Delegate(QObject *parent = 0);
    ~Delegate();

    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
};

2.源文件

#include "Delegate.h"
#include 

Delegate::Delegate(QObject *parent)
{
}

Delegate::~Delegate()
{
}

void Delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    if (index.column() == 1)
    {
        int radio = 5;
        int top = option.rect.top() + radio;
        int left = option.rect.left() + radio;
        int width = option.rect.width() - 2 * radio;
        int height = option.rect.height() - 2 * radio;

        QStyleOptionProgressBar bar;                   //设置参数
        bar.rect.setRect(left, top, width, height);
        bar.state = QStyle::State_Enabled;
        bar.progress = index.data().toInt();
        bar.maximum = 100;
        bar.minimum = 0;
        bar.textVisible = true;
        bar.text = QString(QStringLiteral("当前进度:%1°")).arg(bar.progress);
        bar.textAlignment = Qt::AlignCenter;

        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &bar, painter);
    } else if (index.column() == 2) {
        // 对齐方式
        QStyleOptionViewItem myOption = option;
        myOption.displayAlignment = Qt::AlignRight | Qt::AlignVCenter;

        // 文本颜色  
        QPalette palette;
        palette.setColor(QPalette::Text, QColor(0, 255, 0));

        QApplication::style()->drawItemText(painter, option.rect, myOption.displayAlignment, palette,
            true, index.data().toString(), QPalette::Text);
    } else if (index.column() == 3) {
        // 字体对其方式
        QStyleOptionViewItem myOption = option;
        myOption.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter;

        QPixmap pix;
        pix.load("1.png");

        QRect rect(option.rect.left(), option.rect.top(), 30, 30);
        QApplication::style()->drawItemPixmap(painter, rect, myOption.displayAlignment, pix);

  
    } else {
        QItemDelegate::paint(painter, option, index);
    }
}

3.结果截图


image.png

你可能感兴趣的:(qt自定义委托(进度条))