2011-05-18 47 views
0

为什么这个脚本一启动就打开文件?没有节目显示。PyQt从头开始运行插槽

按下按钮时应打开文件。

如果我删除widget.connect,那么一切正常。但按钮不起作用。

import sys 
import os 
from PyQt4 import QtGui, QtCore 

# open file with os default program 
def openFile(file): 
    if sys.platform == 'linux2': 
     subprocess.call(["xdg-open", file]) 
    else: 
     os.startfile(file) 

# pyQt 
app = QtGui.QApplication(sys.argv) 

widget = QtGui.QWidget() 
button = QtGui.QPushButton('open', widget) 
widget.connect(button, QtCore.SIGNAL('clicked()'), openFile('C:\file.txt')) 

widget.show() 
sys.exit(app.exec_()) 

这是什么问题widget.connect

回答

2

在你的连接线openFile('C:\file.txt')是一个函数openFile的调用。当你将一个信号连接到一个插槽时,你应该通过一个可调用的例如一个函数,但你传递的是openFile的结果。

由于您想要将参数硬编码为openFile,您需要创建一个不带任何参数的新函数,并在被调用时调用openFile('C:\file.txt')。你可以使用lambda表达式来做到这一点,所以你的连接线变为:

widget.connect(button, QtCore.SIGNAL('clicked()'), lambda: openFile('C:\file.txt'))