【已解决】c++ qt如何手动代码绘制一个水平滚动条并设置样式

先看这个水平滚动条的效果吧,效果是用委托构造做的。
【已解决】c++ qt如何手动代码绘制一个水平滚动条并设置样式_第1张图片
如何制作这种水平滚动条,圆角矩形,指定宽度与高度,并且居中对齐,右边有进度字样。这些是笔者本文讨论的话题。那我们就这样开始吧。

问题来源

想要在表格里生成一个水平滚动条,并设置图片中的样式。

问题解决方案

函数定义

class ProgressBarDelegate : public QStyledItemDelegate {
public:
	ProgressBarDelegate(QObject* parent = nullptr);

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

函数实现

ProgressBarDelegate::ProgressBarDelegate(QObject* parent)
	: QStyledItemDelegate(parent)
{
}
void ProgressBarDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
	int progress = index.data(Qt::UserRole + 1).toInt();
	if (progress >= 0 && progress <= 100) {
		painter->save();



		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); // 未选中或没有焦点时的颜色
		}


		// 设置进度条的大小和位置
		int left = option.rect.left() + (option.rect.width() - 10) / 3;
		int top = option.rect.top() + (option.rect.height() - 10) / 3;
		QRect progressBarRect = QRect(left, top, 200, 10);

		painter->setBrush(QBrush(QColor("#DBE7F2")));  // 设置背景颜色
		painter->setPen(Qt::NoPen);  // 不绘制边框
		painter->drawRoundedRect(progressBarRect, 3, 3);  // 绘制圆角矩形,半径为3px

		painter->setBrush(QBrush(QColor("#0080FC")));  // 设置进度颜色
		int width = (progressBarRect.width() * progress) / 100;
		QRect progressRect = progressBarRect.adjusted(0, 0, width - progressBarRect.width(), 0);
		painter->drawRoundedRect(progressRect, 3, 3);  // 绘制圆角矩形,半径为3px

		painter->restore();

		// 绘制进度文本
		QRect textRect = progressBarRect.adjusted(progressBarRect.width() + 5, 0, option.rect.width() - progressBarRect.width(), 0);  // 进度文本的位置在进度条的右边
		painter->setPen(QColor(Qt::black));  // 设置文本颜色
		painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, QString::number(progress) + '%');
	}
	else {
		QStyledItemDelegate::paint(painter, option, index);
	}
}

定义完,函数实现后,那如何使用呢。首先表格先委托

ui.tablePic->setItemDelegateForColumn(ColProgress, new ProgressBarDelegate(this));

委托完毕后,生成该列后,就这样子做

QList<QStandardItem *> newRow;

QStandardItem *chkItem = new QStandardItem();
QStandardItem* progressItem = new QStandardItem();
progressItem->setData(25, Qt::UserRole + 1);
newRow << progressItem;

最后效果就是这样。
【已解决】c++ qt如何手动代码绘制一个水平滚动条并设置样式_第2张图片

你可能感兴趣的:(QT,c++,qt)