QTimeEdit当分钟减少时,如何减少到前一个小时?

时间:2019-07-12 09:05:34

标签: python pyqt pyqt5

我的QTimeEdit显示HH:mm。 MiniuteSection的步骤为15。我的QTimeEdit递增良好。但是当我想减少分钟时,我只能将时间从xx:45更改为xx:30到xx:15和xx-1:45。如您所见,时间xx:00被跳过。无法使其从xx:15递减到xx:00到xx-1:45。有人知道如何解决问题吗?

class FiveteenMinuteTimeEdit(QtWidgets.QTimeEdit):
    def stepBy(self, steps): 
        if self.currentSection() == self.MinuteSection:
            QtWidgets.QTimeEdit.stepBy(self, steps*15)
            t = self.time()
            if t.minute() == 59 and steps >0:
                time = QtCore.QTime()
                time.setHMS(t.hour()+1,0,0)
                self.setTime(time)
            if t.minute() == 0 and steps <0:
                time = QtCore.QTime()
                time.setHMS(t.hour()-1,45,0)
                self.setTime(time)
        else:
            QtWidgets.QTimeEdit.stepBy(self, steps)

1 个答案:

答案 0 :(得分:1)

您只需要增加60 * 15 * step秒,为了更好的实现,当显示的时间在适当的限制范围内时,您必须启用上下箭头。{p> 3}

from PyQt5 import QtWidgets


class FiveteenMinuteTimeEdit(QtWidgets.QTimeEdit):
    def stepBy(self, step):
        if self.currentSection() == QtWidgets.QDateTimeEdit.MinuteSection:
            self.setTime(self.time().addSecs(60 * 15 * step))
            return
        super(FiveteenMinuteTimeEdit, self).stepBy(step)

    def stepEnabled(self):
        if self.currentSection() == QtWidgets.QDateTimeEdit.MinuteSection:
            if self.minimumTime() < self.time() < self.maximumTime():
                return (
                    QtWidgets.QAbstractSpinBox.StepUpEnabled
                    | QtWidgets.QAbstractSpinBox.StepDownEnabled
                )
        return super(FiveteenMinuteTimeEdit, self).stepEnabled()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = FiveteenMinuteTimeEdit()
    w.show()
    sys.exit(app.exec_())

更新

以下代码允许从00:00更改为23:45,从00:00更改为23:00。

from PyQt5 import QtWidgets


class FiveteenMinuteTimeEdit(QtWidgets.QTimeEdit):
    def stepBy(self, step):
        d = {
            QtWidgets.QTimeEdit.SecondSection: step,
            QtWidgets.QTimeEdit.MinuteSection: 60 * 15 * step,
            QtWidgets.QTimeEdit.HourSection: 60 * 60 * step,
        }
        seconds = d.get(self.currentSection(), 0)
        self.setTime(self.time().addSecs(seconds))
        if self.currentSection() == QtWidgets.QTimeEdit.MSecSection:
            self.setTime(self.time().addMSecs(step))
        elif self.currentSection() == QtWidgets.QTimeEdit.AmPmSection:
            super(FiveteenMinuteTimeEdit, self).stepBy(step)

    def stepEnabled(self):
        return (
            QtWidgets.QAbstractSpinBox.StepUpEnabled
            | QtWidgets.QAbstractSpinBox.StepDownEnabled
        )


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = FiveteenMinuteTimeEdit()
    w.setDisplayFormat("hh mm")
    w.show()
    sys.exit(app.exec_())