pyqt 使用問題總結

環境:py2.7.14 + pyqt4

1.在使用下列方式創建信號連接時

self.connect(button, QtCore.SIGNAL('clicked()'),self.slot1(arg))

報錯提示爲:

TypeError: arguments did not match any overloaded call:
  QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'
  QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 3 has unexpected type 'NoneType'


解析:

這裏的slot1()是一個函數,當槽函數是自定義的函數時要這樣,用lambda: self.slot1(arg)替換self.slot1(arg)即可

或者這個slot1只是一個method,不需要參數時,用slot1替換slot即可。

看到這,其本質是python調用函數時加不加括號的區別。

def ab():
    return  1+2
print ab
print ab()

結果:

<function ab at 0x00000000035AB748>
3

綜上,其區別在與不加括號時,調用的時這個函數的,這個對象的內存地址,

加括號時你調用的是這個函數的運行結果

參考StackOverflow:

person a:The connect() method expects a callable argument. When you write self.Soft_Memory() you are making a call to that method, and the result of that call (None, since you don't explicitly return anything) is what is being passed to connect().

person b:You want to pass a reference to the method itself.

you should use a reference of the method, instead of calling it:

self.PB1.clicked.connect(self.Soft_Memory)

However, you might often need to pass arguments on those functions (I certainly do). On those situations, if you need to use args there's a workaround by using lambda.

self.PB1.clicked.connect(lambda: myfunction(self, arg1, True, "example", arg4))

參考鏈接:

https://stackoverflow.com/questions/45793966/clicked-connect-error

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章