'PyQt connect() NameError
I'm learning how to use PyQt correctly.
Trying to make a window Class with a button that prints a line.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class Window:
def __init__(self, args):
#initializes PyQt
self.app = QApplication(args)
self.widget = QWidget()
self.widget.setWindowTitle("PyQt5 Example")
#create label
self.textLabel = QLabel(self.widget)
self.textLabel.setText("Hello World!")
self.textLabel.move(110,85)
#create button
self.button = QPushButton(self.widget)
self.button.setText("Click me!")
self.button.move(64,32)
#connect button to a method
self.button.clicked.connect(buttonClicked)
#set starting position on monitor (50, 50) and window size (320, 200)
self.widget.setGeometry(50,50,320,200)
#show window
self.widget.show()
sys.exit(app.exec_())
def buttonClicked(self):
print("Button clicked!")
if __name__ == '__main__':
print(sys.argv)
app = Window(sys.argv)
When I run the code I get, NameError: name 'buttonClicked' is not defined
Double checking all indentation and object syntax it's not apparent to me what is wrong. What's weirder is that such syntax works completely fine when outside of a class.
E.g the following code returns no NameError,
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
def window():
app = QApplication(sys.argv)
widget = QWidget()
button1 = QPushButton(widget)
button1.setText("Button1")
button1.move(64,32)
button1.clicked.connect(button1_clicked)
button2 = QPushButton(widget)
button2.setText("Button2")
button2.move(64,64)
button2.clicked.connect(button2_clicked)
widget.setGeometry(50,50,320,200)
widget.setWindowTitle("PyQt5 Button Click Example")
widget.show()
sys.exit(app.exec_())
def button1_clicked():
print("Button 1 clicked")
def button2_clicked():
print("Button 2 clicked")
if __name__ == '__main__':
window()
Solution 1:[1]
I wasn't properly referencing the method. when calling self.button.clicked.connect(buttonClicked).
What is required is self.button.clicked.connect(self.buttonClicked)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | hunter |
