如何将图像和 QProgressBar 放入 QTableView?

Mar*_*rco 4 c++ qt

我正在开发某种下载管理器并在 QTableView 中显示文件名、大小和剩余字节。现在我想用 QProgressBar 可视化进度并显示图像(以指示它是下载还是上传)。如何添加或显示QProgressBar和图像的QTableView中?

Căt*_*tiș 5

如果您使用的是QTableView,我认为您使用的是链接到此视图的模型。

一种解决方案是使用委托(请参阅QItemDelegate)来绘制进度,在QItemDelegate::paint您必须定义的方法中,使用QStyle小部件 ( widget->style()) 来绘制进度(QStyle::drawControlQStyle::CE_ProgressBarContents控件标识符一起使用)。

查看示例 Star Delegate 中的文档,了解如何为您需要的列定义委托。

后期编辑:定义委托绘制方法的示例(代码草图,没有真正测试过,以它为原则,不完全工作)。

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);
}
Run Code Online (Sandbox Code Playgroud)