开发者

PyQt running slot from the start

Why this script opens file as soon as it is launched? No program is showed.

It is supposed to open file when the button is pressed.

If I remove widget.connect, then everything is ok. But the butto开发者_运维知识库n does not working.

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_())

What is wrong with this widget.connect?


In your connect line openFile('C:\file.txt') is a call to the function openFile. When you connect a signal to a slot you're supposed to pass a callable, e.g. a function but you're passing the result of openFile.

As you want to hard code the parameter to openFile you need to create a new function which takes no arguments and when called calls openFile('C:\file.txt'). You can do this using a lambda expression, so your connect line becomes:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜