Home » PyQt5 QTimeEdit widget

PyQt5 QTimeEdit widget

by maxguy71

In this article we will look at the PyQt QTimeEdit widget.

The PyQt5 QTimeEdit widget is a way for the user to enter in a Time as an input.

Lets look at the methods that are available

Methods

Method Description
time() Returns the current time displayed on the widget,
setTime() Used to set the currently displayed time.
setTimeRange() allows you to limit the range of time you can choose.

 

Examples

 

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 Example')

        timeEdit = QTimeEdit(self)
        #set to current time
        timeEdit.setTime(QTime.currentTime())
        #set the time range
        timeEdit.setTimeRange(QTime(6, 00, 00), QTime(22, 00, 00))
        timeEdit.setDisplayFormat('hh:mm:ss')
        vbox = QVBoxLayout()
        vbox.addWidget(lbl)
        vbox.addWidget(timeEdit)
        vbox.addStretch()

        self.setLayout(vbox)

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


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Retrieving values

We can return the values from the QTimeEdit

When we pass a time value, we have to use the QTime to convert it into an appropriate format and when we return the date value, we use toPyTime to print it in a more readable format.

It sounds complicated but you can see in the complete code example we have the following showTime() function which is called when the button is pressed

def showTime():
    print(timeEdit.time().toPyTime())

Here is the complete example

 

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QTime
import sys
 
def showTime():
    print(timeEdit.time().toPyTime())
 
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(300, 300, 300, 200)
win.setWindowTitle("QTimeEdit Example")
 
timeEdit = QtWidgets.QTimeEdit(win)
#set to current date
timeEdit.setTime(QTime.currentTime())
#set the time range
timeEdit.setTimeRange(QTime(6, 00, 00), QTime(22, 00, 00))
timeEdit.setDisplayFormat('hh:mm:ss')
timeEdit.move(50,50)
 
button = QtWidgets.QPushButton(win)
button.setText("Press me")
button.clicked.connect(showTime)
button.move(50,100)
 
win.show()
sys.exit(app.exec_())

This displays the following

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More