4

I want to set text as label when button is clicked. self.labl.setText does work normally, but it doesn't work when it is in button function. I have read all the similar questions here, but still didn't solve the problem :(

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'title'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()


    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.labl = QLabel(self)
        self.labl.setText('abc')

        button = QPushButton('button', self)        
        button.move(170,300)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        self.labl = QLabel(self)
        self.labl.setText('abc')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
anna
  • 65
  • 1
  • 1
  • 4

2 Answers2

8

The problem is simple, you are creating another QLabel, and that is not what you want, you just have to update the text.

@pyqtSlot()
def on_click(self):
    self.labl.setText('some text')
    self.labl.adjustSize()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0

I also see you are stating the Qlabel twice.

Write this in the init() function:

global labl
labl = QLabel("Original Text", self)

In the on_click function, change your code to look this way:

def on_click(self):
     labl.set text("I have been clicked") 
     labl.adjustSize() 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83