Search code examples
pythonformspyqt5

How do I change the font of label roles for the form layout in PyQt5?


I want all the text in a window I'm generating in PyQT5 to be courier. However, when I add rows to a form layout and add the label roles, these labels do not appear in courier. Here is my code:

self.vertical.addLayout(self.form)
self.user_name = QLineEdit(self)
self.user_name.setFont(QtGui.QFont('Courier', 15))
self.password = QLineEdit(self)
self.password.setFont(QtGui.QFont('Courier', 15))
self.form.addRow('username', self.user_name)
self.form.addRow('password', self.password)

From the code, I cannot get the form labels 'username' and 'password' to be in courier. There must be a simple fix, but I am just not finding it. I appreciate anyone taking the time to help! See the following picture and note that 'username' and 'password' are not in courier:

enter image description here


Solution

  • Try something like this:

    from PyQt5 import QtGui, QtWidgets
    
    class MyWindow(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
    
            self.form = QtWidgets.QFormLayout()
            self.vertical = QtWidgets.QVBoxLayout(self)
            self.vertical.addLayout(self.form)
    
            self.user_name = QtWidgets.QLineEdit(self)
            self.user_name.setFont(QtGui.QFont('Courier', 15))
            self.password = QtWidgets.QLineEdit(self)
            self.password.setFont(QtGui.QFont('Courier', 15))
    
            # Create labels with the desired font
            username_label = QtWidgets.QLabel('username')
            username_label.setFont(QtGui.QFont('Courier', 15))
            password_label = QtWidgets.QLabel('password')
            password_label.setFont(QtGui.QFont('Courier', 15))
    
            self.form.addRow(username_label, self.user_name)
            self.form.addRow(password_label, self.password)
    
            self.setLayout(self.vertical)
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication([])
        window = MyWindow()
        window.show()
        app.exec_()
    

    I get as a result:

    enter image description here