首页 > 解决方案 > 进度条代表垂直填充而不是水平填充

问题描述

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

但是,进度条是从下到上填满的,见附件截图(而且,文本没有显示!): 截屏 相反,我希望它从左到右填满,我相信这应该是通过设置的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_())

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

标签: pythonqtpysideqtwidgets

解决方案


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

您正在寻找的是orientation变量,自 Qt 5.5 以来已被认为已过时,有利于适当的QStyle.State标志:

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

推荐阅读