PySide无法连接signal clicked()

2024-09-30 14:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个应用程序,它应该在点击按钮后打开一个web浏览器地址。主要功能如下:

class MainWindow(QtGui.QDialog):
    def __init__( self, parent = None ):
        super( MainWindow, self ).__init__( parent = parent )
        self.button_layout = QtGui.QHBoxLayout(self)
        self.webButton = PicButton(QtGui.QPixmap("images/button.png"))
        self.filmButton.clicked.connect(openWebpage("http://some.web.adress"))
        self.button_layout.addWidget(self.webButton)

打开web浏览器的功能如下所示:

^{pr2}$

运行此代码后,没有可见的应用程序窗口,web浏览器立即启动,控制台返回:

Failed to connect signal clicked().

与此按钮连接的简单功能可以正常工作(例如,将文本打印到控制台)。有什么想法吗?在


Tags: self功能web应用程序initconnect浏览器button
2条回答

正如人们早些时候所说的-使用lambda,或者使用一个普通的slot,这样(至少对我来说)更具可读性。在

def __init__(self):
    self.filmButton.clicked.connect(self._film_button_clicked)

@pyqtSlot() # note that this is not really necessary
def _film_button_clicked(self):
    self.openWebpage('http://some.web.adress')

要在槽中传递参数,需要构造lambda表达式:

self.filmButton.clicked.connect(lambda: openWebpage("http://some.web.adress"))

为了进一步解释这一点,connect()方法接受一个可调用对象作为其参数。lambda表达式基本上是一个匿名函数,就是这样一个可调用对象。您还可以将函数调用包装在functools模块的partial()方法中以实现相同的功能。有关Python可调用内容的更多信息,请参见What is a "callable" in Python?

相关问题 更多 >