生活随笔
收集整理的這篇文章主要介紹了
pyqt5讲解12:自定义参数 (给信号传入参数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在pyqt編程過程中,經常會遇到給槽函數傳遞自定義參數的情況,比如有一個信號與槽函數的連接是
button1
.clicked
.connect
(shou_page
)
對于clicked 信號來說,是沒有參數的。
對于shou_page 是可以有參數的
如:
def show_page(slef
,name
):print(name
,"點啦")
一個有參數,一個無參數 ,運行起來肯定有錯。
解決方法1:
lambda
"""【簡介】部件中的信號槽傳遞,使用lambda表達式傳參數示例"""from PyQt5
.QtWidgets
import QMainWindow
, QPushButton
, QWidget
, QMessageBox
, QApplication
, QHBoxLayout
import sys
class WinForm(QMainWindow
):def __init__(self
, parent
=None):super(WinForm
, self
).__init__
(parent
)self
.setWindowTitle
("信號和槽傳遞額外參數例子")button1
= QPushButton
('Button 1')button2
= QPushButton
('Button 2')button1
.clicked
.connect
(lambda: self
.onButtonClick
(1))button2
.clicked
.connect
(lambda: self
.onButtonClick
(2))layout
= QHBoxLayout
()layout
.addWidget
(button1
)layout
.addWidget
(button2
)main_frame
= QWidget
()main_frame
.setLayout
(layout
)self
.setCentralWidget
(main_frame
)def onButtonClick(self
, n
):print('Button {0} 被按下了'.format(n
))QMessageBox
.information
(self
, "信息提示框", 'Button {0} clicked'.format(n
))if __name__
== "__main__":app
= QApplication
(sys
.argv
)form
= WinForm
()form
.show
()sys
.exit
(app
.exec_
())
點擊 button1
彈出
解釋:
關鍵行 傳入參數1
button1.clicked.connect(lambda: self.onButtonClick(1))
解決方法2:
partial函數
"""【簡介】部件中的信號槽傳遞,使用partial函數傳參數示例"""from PyQt5
.QtWidgets
import QMainWindow
, QPushButton
, QWidget
, QMessageBox
, QApplication
, QHBoxLayout
import sys
from functools
import partial
class WinForm(QMainWindow
):def __init__(self
, parent
=None):super(WinForm
, self
).__init__
(parent
)self
.setWindowTitle
("信號和槽傳遞額外參數例子")button1
= QPushButton
('Button 1')button2
= QPushButton
('Button 2')button1
.clicked
.connect
(partial
(self
.onButtonClick
, 1))button2
.clicked
.connect
(partial
(self
.onButtonClick
, 2))layout
= QHBoxLayout
()layout
.addWidget
(button1
)layout
.addWidget
(button2
)main_frame
= QWidget
()main_frame
.setLayout
(layout
)self
.setCentralWidget
(main_frame
)def onButtonClick(self
, n
):print('Button {0} 被按下了'.format(n
))QMessageBox
.information
(self
, "信息提示框", 'Button {0} clicked'.format(n
))if __name__
== "__main__":app
= QApplication
(sys
.argv
)form
= WinForm
()form
.show
()sys
.exit
(app
.exec_
())
關鍵代碼:
from functools import partial
button1.clicked.connect(partial(self.onButtonClick, 1))
button2.clicked.connect(partial(self.onButtonClick, 2))
代碼來源于:書籍 pyqt5快速開發與實戰
記錄學習筆記
總結
以上是生活随笔為你收集整理的pyqt5讲解12:自定义参数 (给信号传入参数)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。