Reputation: 2644
So, I am new to python programming. I have started to implement a UI in pyqt5 and there I have a button and I want to react when the user clicks it.
According to this Link I should simply write btn.clicked.connect(self.buton_pressed)
however I get the message "Cannot find reference connect in function". (The surrounding code is at the end of the question)
So I googled a bit and all I found is that it should just work that way. I just don't get why it does not. I found this Stackoverflow question which also describes the old variant of how to do it. That did not work either, after some googeling I found out that it is no longer supported in pyqt5 or in some other package.
The function where I try to connec to the event:
def __add_button(self, text: str, layout: QLayout):
btn = QPushButton(text, self)
layout.addWidget(btn)
btn.clicked.connect(self.button_pressed)
# TODO: fix this.
return btn
The code where the GUI is generated and the function called, in the __init__
function
lblhm = QLabel("Hauptmessung", self)
layout.addWidget(lblhm)
self.__hm_b = self.__add_button("Messung öffnen", layout)
self.__hm_config_b = self.__add_button("Configruation öffnen", layout)
lblzm = QLabel("Zusatzmessung", self)
layout.addWidget(lblzm)
self.__zm_b = self.__add_button("Messung öffnen", layout)
self.__zm_config_b = self.__add_button("Configuration öffnen", layout)
The button_pressed function is not yet implemented, but it is supposed to open a openFile dialog for file selection.
According to this post i could just connect after returning the function, but then i would have to write it 4 times which is not very nice. Isn't the signal bound to the object not to the variable?
Thankful for any help :)
Upvotes: 2
Views: 25766
Reputation: 2160
It's hard to understand your problem since you don't provide us with a working example, i.e. a peace of code one can run "as is". Something like this:
from PyQt4 import QtCore, QtGui
class MyWindow(QtGui.QWidget):
def __init__(self):
super().__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
lblhm = QtGui.QLabel("Hauptmessung", self)
layout.addWidget(lblhm)
self.__hm_b = self.__add_button("Messung öffnen", layout)
self.__hm_config_b = self.__add_button("Configruation öffnen", layout)
lblzm = QtGui.QLabel("Zusatzmessung", self)
layout.addWidget(lblzm)
self.__zm_b = self.__add_button("Messung öffnen", layout)
self.__zm_config_b = self.__add_button("Configuration öffnen", layout)
def button_pressed(self):
print('Button pressed')
def __add_button(self, text: str, layout: QtGui.QLayout):
btn = QtGui.QPushButton(text, self)
layout.addWidget(btn)
btn.clicked.connect(self.button_pressed)
return btn
if __name__== '__main__':
import sys
app = QtGui.QApplication(sys.argv)
wnd = MyWindow()
wnd.show()
sys.exit(app.exec_())
There's no problem with this code under PyQt4
. Does it work for with PyQt5
?
Upvotes: 4