sender() returns None ?
-
My code is:
from PySide6.QtUiTools import QUiLoader from PySide6.QtWidgets import QMainWindow from PySide6 import QtWidgets class Solar(QMainWindow): def __init__(self): super().__init__() self.main_ui = QUiLoader().load('test.ui') self.main_ui.pushButton.clicked.connect(self.ppt) self.main_ui.pushButton_2.clicked.connect(self.ppt) self.main_ui.pushButton_3.clicked.connect(self.ppt) def ppt(self): print(self) print('---------------') print(self.main_ui) print('---------------') print(self.sender()) print('---------------') print(self.main_ui.sender()) if __name__ == '__main__': app = QtWidgets.QApplication() scf = Solar() scf.main_ui.show() app.exec()
And it shows as:
The result printed is:<__main__.Solar(0x1891d3d2510) at 0x000001891DD3A6C0> --------------- <PySide6.QtWidgets.QMainWindow(0x1891d363a70, name="MainWindow") at 0x000001891DD3A780> --------------- <PySide6.QtWidgets.QPushButton(0x1891d363c80, name="pushButton_2") at 0x000001891DD3A9C0> --------------- None
Why main_ui.sender() returns
None
? To get the signal realted to a certain button, do I have to let my customClass
inheritQMainWindow
? -
@feiyuhuahuo said in sender() returns None ?:
print(self.main_ui.sender())
This is wrong.
It should be simply sender(). -
@jsulm If my custom class does not inherit
QMainWindow
, like this,class Solar: def __init__(self): super().__init__() self.main_ui = QUiLoader().load('test.ui') self.main_ui.pushButton.clicked.connect(self.ppt) def ppt(self): print(self.main_ui.sender()) if __name__ == '__main__': app = QtWidgets.QApplication() scf = Solar() scf.main_ui.show() app.exec()
The result is None, why? Why
self.main_ui.sender()
is useless? It is also aQMainWindow
object. -
@feiyuhuahuo said in sender() returns None ?:
If my custom class does not inherit QMainWindo
Try to inherit from QObject at least if you want to use signals/slots
-
@feiyuhuahuo
In addition to what @jsulm has been telling you about how to accesssender()
.Why do you want to use
sender()
at all? It's OK if you want to call it for, say, debugging purposes to see where your slot has been called from. But it is no longer the best way to access the sender in production code. For that you should now use a lambda for the slot in yourconnect()
statements, passing an explicit parameter of the sender. I think in Python it would be:self.main_ui.pushButton.clicked.connect(lambda btn=self.main_ui.pushButton: self.ppt(btn)) def ppt(self, btn): print(btn)
Also with this approach you do not have to make
Solar
inherit fromQObject
.