python - 使进度条以 5 Pyside 为增量对齐

标签 python pyside qprogressbar

我创建了一个自定义进度栏,允许用户单击并拖动以选择所需的百分比值。我想知道如何让它以 5 为增量进行调整?理想情况下,我会将其设置为用户在使用控件时可以设置的属性。

enter image description here

import sys
from PySide import QtGui, QtCore

class QProgressBarPro(QtGui.QProgressBar):

    barClicked = QtCore.Signal()

    def __init__(self, parent=None):
        super(QProgressBarPro, self).__init__(parent)
        self.default_value = 50.0
        self.lmb_pressed = False

    def set_value_from_cursor(self, xpos):
        width = self.frameGeometry().width()
        percent = float(xpos) / width
        val = self.maximum() * percent
        self.setValue(val)

    def mousePressEvent(self, event):
        self.barClicked.emit()
        mouse_button = event.button()

        if mouse_button == QtCore.Qt.RightButton:
            self.setValue(self.default_value)
        else:
            xpos = event.pos().x()
            self.set_value_from_cursor(xpos)
            self.lmb_pressed = True

    def mouseReleaseEvent(self, event):
        self.lmb_pressed = False

    def mouseMoveEvent(self, event):
        if self.lmb_pressed:
            xpos = event.pos().x()
            self.set_value_from_cursor(xpos)

# DEMO
class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.ui_progress = QProgressBarPro()
        self.ui_progress.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
        self.ui_progress.setValue(10)

        gdl = QtGui.QVBoxLayout()
        gdl.addWidget(self.ui_progress)
        self.setLayout(gdl)

        self.resize(300, 300)
        self.setWindowTitle('Tooltips')    
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

最佳答案

看来你只需要在设置之前调整该值:

def set_value_from_cursor(self, xpos):
    width = self.frameGeometry().width()
    percent = float(xpos) / width
    val = self.maximum() * percent
    if val % 5:
        val += 5 - (val % 5)
    self.setValue(val)

关于python - 使进度条以 5 Pyside 为增量对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926572/

相关文章:

python - 模型的输出张量必须是 Keras 张量

python - 多种语言的名称实体识别 (NER)

python - 相当于 QT 的 wxStaticBox

python - 在 QProgressBar 内添加文本和完成百分比

python - 在 PyQt5 的方法中添加进度条

Python Paramiko - 运行命令

python - 如何使用pickle保存聊天机器人模型

python - QtDesigner 和 PySide : QTableWidget don't get accessible

pyside - 如何在不触发 PySide 中的 valueChanged 回调的情况下设置小部件的值?

c++ - Qt Progressbar 增加超过它应该的