QTimeEdit

The QTimeEdit widget allows users select and edit time.

We’ll create a QTimeEdit object in this example and set it to display as the current time.

For further information, check QTimeEdit official document .


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QTimeEdit, QVBoxLayout
from PyQt5.QtCore import QTime


class MyApp(QWidget):

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

        self.initUI()

    def initUI(self):

        lbl = QLabel('QTimeEdit')

        timeedit = QTimeEdit(self)
        timeedit.setTime(QTime.currentTime())
        timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
        timeedit.setDisplayFormat('hh:mm:ss')

        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(timeedit)
        vbox.addStretch()

        self.setLayout(vbox)

        self.setWindowTitle('QTimeEdit')
        self.setGeometry(300, 300, 300, 200)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Time editing widget(QTimeEdit) appears on the window.


Description

timeedit = QTimeEdit(self)
timeedit.setTime(QTime.currentTime())
timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))

Create a time edit widget using the QTimeEdit class.

Type QTime.currentTime() in the setTime method so that the current time is displayed when the program is run.

setTimeRange allows users to limit the range of time you can select. The minimum time is set to 00:00:00:000 milliseconds by default, and the maximum time is set to 23:59:59:999 milliseconds.


timeedit.setDisplayFormat('hh:mm:ss')

We used setDisplayFormat method to display time in the format ‘hhh:mm:ss’.


vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(timeedit)
vbox.addStretch()

self.setLayout(vbox)

Use the vertical box layout to position the label and time editing widget vertically, and set it as the layout of the entire widget.


Results

../_images/4_17_qtimeedit.png ../_images/4_17_qtimeedit_mac.png

Figure 5-15. Use QTimeEdit for time editing widget.


Prev/Next

Prev :