我正在开发某种下载管理器并在 QTableView 中显示文件名、大小和剩余字节数。现在我想用 QProgressBar 可视化进度并显示图像(以指示它是下载还是上传)。如何在 QTableView 的内部添加或显示 QProgressBar 和图像?
最佳答案
如果您使用的是 QTableView
,我假设您使用的是链接到此 View 的模型。
一个解决方案是使用委托(delegate)(参见QItemDelegate
)来绘制进度,在您必须定义的QItemDelegate::paint
方法中,使用QStyle
小部件 (widget->style()
) 绘制进度(使用 QStyle::drawControl
和 QStyle::CE_ProgressBarContents
作为控件标识符)。
查看示例 Star Delegate 的文档,了解如何为您需要的列定义委托(delegate)。
后期编辑:定义delegate paint方法的例子(code sketch,未真正测试,以它为原理,未完全运行)。
void MyDelegate::paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QStyleOptionProgressBar progressStyle;
progressStyle.rect = option.rect; // Maybe some other initialization from option would be needed
// For the sake of the example, I assume that the index indicates the progress, and the next two siblings indicate the min and max of the progress.
QModelIndex minIndex = index.sibling( index.row(), index.column() + 1);
QModelIndex maxIndex = index.sibling( index.row(), index.column() + 2);
progressStyle.minimum = qvariant_cast< int>( minIndex.data( Qt::UserRole));
progressStyle.maximum = qvariant_cast< int>( maxIndex.data( Qt::UserRole));
progressStyle.progress = qvariant_cast< int>( index.data( Qt::UserRole));
progressStyle.textVisible = false;
qApp->style()->drawControl( QStyle::CE_ProgressBarContents, progressStyleOption, painter);
}
关于c++ - 如何将图像和 QProgressBar 放入 QTableView 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656306/