进度条委托垂直填充而不是水平填充

问题描述

我正在尝试使用带有自定义绘制方法的 QTreeWidgetQStylesItemDelegate 中绘制一列,以呈现进度条的外观。

然而,进度条是从下往上填满的,见附件截图(而且,文字没有显示!):

screenshot

相反,我希望它从左到右填充,我相信这应该通过 QStyleOptionProgressBar.direction?

设置

这是生成我的屏幕截图的 MRE:

import sys

from PySide6 import (
    QtCore,QtWidgets
)


class MyDelegate(QtWidgets.QStyledItemDelegate):

    def paint(self,painter,option,index):
        progress_bar_option = QtWidgets.QStyleOptionProgressBar()
        progress_bar_option.rect = option.rect
        progress_bar_option.state = QtWidgets.QStyle.State_Enabled
        progress_bar_option.direction = QtCore.Qt.LayoutDirection.LeftToRight
        progress_bar_option.fontMetrics = QtWidgets.QApplication.fontMetrics()

        progress_bar_option.minimum = 0
        progress_bar_option.maximum = 100
        progress_bar_option.textAlignment = QtCore.Qt.AlignCenter
        progress_bar_option.textVisible = True

        progress_bar_option.progress = 66
        progress_bar_option.text = 'demo'

        QtWidgets.QApplication.style().drawControl(QtWidgets.QStyle.CE_ProgressBar,progress_bar_option,painter)


class MyWidget(QtWidgets.QTreeWidget):
    def __init__(self,parent=None):
        super().__init__(parent)

        self.examplerow = QtWidgets.QTreeWidgetItem(self)

        self.setHeaderLabels(['Col 1','Col 2','Col 3'])
        self.setAlternatingRowColors(True)

        self.examplerow.setText(0,'Content in first column')
        self.examplerow.setText(1,'second')
        self.examplerow.setText(2,str(3))

        delegate = MyDelegate(self)

        self.setItemDelegateForColumn(2,delegate)


if __name__ == "__main__":
    app = QtWidgets.QApplication()

    widget = MyWidget()

    window = QtWidgets.QMainWindow()
    window.setCentralWidget(widget)
    window.resize(800,600)
    window.show()

    sys.exit(app.exec_())

改变进度条方向的正确方法是什么?

解决方法

direction 变量与进度条方向无关,因为它对所有 QStyleOption 类都是通用的,并且与文本布局方向有关(对于希伯来语或阿拉伯语等语言,从左到右或从右到左)。

您要查找的是 orientation 变量,该变量自 Qt 5.5 起就被认为已过时,以支持适当的 QStyle.State 标志:

# ...
progress_bar_option.state = QtWidgets.QStyle.State_Enabled
progress_bar_option.state |= QtWidgets.QStyle.State_Horizontal

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...