When specifying a signal in PySide, you can usually specify it as follows.
signal_without_arg
# (object).(signal).connect(slot)
self.button1.clicked.connect(self.without_arg)
However, like clicked, A little care should be taken if the signal may have optional arguments. With the above specification method, it is interpreted as a signal without optional arguments, so if you want to use a signal with optional arguments, you need to specify the type of the argument explicitly passed as follows.
signal_with_arg
self.button2.clicked[bool].connect(self.with_arg)
The code for checking the behavior is as follows. If you click button1 / button2, you can see that each button is bound to a slot (without_arg / with_arg) with a different number of arguments.
onoff_button.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PySide.QtGui import QApplication, QMainWindow, QWidget, QPushButton,\
QVBoxLayout
class OnOffButtonWidget(QWidget):
def __init__(self):
super(OnOffButtonWidget, self).__init__()
self.__init_ui()
self.__init_event()
def __init_ui(self):
self.button1 = QPushButton('button1', self)
self.button2 = QPushButton('button2', self)
self.button1.setCheckable(True)
self.button2.setCheckable(True)
vbox = QVBoxLayout()
vbox.addWidget(self.button1)
vbox.addWidget(self.button2)
self.setLayout(vbox)
def __init_event(self):
self.button1.clicked.connect(self.without_arg)
self.button2.clicked[bool].connect(self.with_arg)
def without_arg(self):
print 'without_arg'
def with_arg(self, clicked):
print 'with arg:{0}'.format(clicked)
def main():
app = QApplication(sys.argv)
window = QMainWindow()
window.setCentralWidget(OnOffButtonWidget())
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
(Output when the button is clicked)
output
without_arg (Output when button1 is clicked)
with arg:True (Output when button2 is clicked)
Since you can see the default value by looking at the document (ex. Clicked ([checked = false])), you can specify a common slot by using the default argument.
with_optional
def __init_event(self):
self.button1.clicked.connect(self.with_optional)
self.button2.clicked[bool].connect(self.with_optional)
def with_optional(self, clicked=False):
print 'with arg:{0}'.format(clicked)
Activated In some cases, the name and the number of arguments are the same, but only the argument type is different. In that case, it is necessary to specify the type.
with_same
def __init_event(self):
self.combo.activated[str].connect(self.on_activated)
self.combo.activated[int].connect(self.on_activated_init)
def on_activated(self, text):
self.label.setText(text)
def on_activated_init(self, index):
print index
Recommended Posts