PyQt5 - How to change text of pre-existing label

PyQt5 - How to change text of pre-existing label

In PyQt5, you can easily change the text of a pre-existing label using the setText method. Here's a simple example to demonstrate this:

  1. Create a basic PyQt5 application with a label and a button.
  2. Connect the button's click signal to a method that changes the label's text.

Here's a step-by-step implementation:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout

class AppDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # Create a QVBoxLayout to arrange widgets vertically
        layout = QVBoxLayout()

        # Create a label and add it to the layout
        self.label = QLabel("Original Text", self)
        layout.addWidget(self.label)

        # Create a button and connect its clicked signal to changeText method
        self.btn = QPushButton("Change Text", self)
        self.btn.clicked.connect(self.changeText)
        layout.addWidget(self.btn)

        # Set the window's layout
        self.setLayout(layout)

        self.setWindowTitle('PyQt5 Change Label Text')
        self.show()

    def changeText(self):
        """Change label's text."""
        self.label.setText("Text Changed!")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = AppDemo()
    sys.exit(app.exec_())

When you run the above code, a window with a label displaying "Original Text" and a button labeled "Change Text" will appear. Clicking the button will change the label's text to "Text Changed!".


More Tags

bookmarklet pushviewcontroller aws-sdk azure-powershell sapui5 httpcontext camelcasing handler custom-data-attribute typeorm

More Programming Guides

Other Guides

More Programming Examples