简体   繁体   中英

Make QProgress bar snap in increments of 5 Pyside

I have created a custom progress bar which allows users to click and drag to choose their desired percent value. I was wondering how can I make it snap in increments of 5? Ideally I'll make this a property the user can set when using the control.

在此处输入图片说明

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()

It seems you just need to adjust the value before setting it:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM