我正在使用 pyqt4 在 python 2.7 中构建一个 GUI。我想将按钮链接到脚本,有人向我提供了以下代码:
from PyQt4 import QtGui
import sys
# --- functions ---
def my_function(event=None):
print 'Button clicked: event:', event
print linetext.text()
# run your code
# --- main ---
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
# add "layout manager"
vbox = QtGui.QVBoxLayout()
window.setLayout(vbox)
# add place for text
linetext = QtGui.QLineEdit(window)
vbox.addWidget(linetext)
# add button
button = QtGui.QPushButton("Run", window)
vbox.addWidget(button)
# add function to button
button.clicked.connect(my_function)
window.show()
sys.exit(app.exec_())
我不明白你为什么要传递
event=None
作为 my_function
的参数。当我运行没有事件部分的脚本时,它工作正常。
不需要。
在Qt中,事件和信号/槽是两个独立的系统。一般来说,事件最终来自应用程序的“外部”(例如键盘按下、鼠标移动等),而信号则来自应用程序的“内部”。
单击是事件的组合(鼠标按下 + 鼠标释放),这些事件最初由 Qt 内部处理。然后,事件处理程序会在适当的时候发出 clicked
信号。
clicked
信号实际上发送其checked-state(即
True
或False
),而不是事件对象。但这与您的脚本并不真正相关(也就是说,您不需要为其提供参数)。