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

2024-04-25 10:57:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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)

Tags: andselfiftime时间stepsxxhour
1条回答
网友
1楼 · 发布于 2024-04-25 10:57:01

您只需添加60 * 15 * step秒,而且为了更好地实现,当显示的时间处于覆盖stepEnabled()方法的适当限制时,必须启用向上和向下箭头。你知道吗

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

相关问题 更多 >