生活随笔
收集整理的這篇文章主要介紹了
pyqt5讲解12:自定义参数 (给信号传入参数)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在pyqt編程過程中,經(jīng)常會遇到給槽函數(shù)傳遞自定義參數(shù)的情況,比如有一個信號與槽函數(shù)的連接是
button1
.clicked
.connect
(shou_page
)
對于clicked 信號來說,是沒有參數(shù)的。
對于shou_page 是可以有參數(shù)的
如:
def show_page(slef
,name
):print(name
,"點(diǎn)啦")
一個有參數(shù),一個無參數(shù) ,運(yùn)行起來肯定有錯。
解決方法1:
lambda
"""【簡介】部件中的信號槽傳遞,使用lambda表達(dá)式傳參數(shù)示例"""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
("信號和槽傳遞額外參數(shù)例子")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_
())
點(diǎn)擊 button1
彈出
解釋:
關(guān)鍵行 傳入?yún)?shù)1
button1.clicked.connect(lambda: self.onButtonClick(1))
解決方法2:
partial函數(shù)
"""【簡介】部件中的信號槽傳遞,使用partial函數(shù)傳參數(shù)示例"""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
("信號和槽傳遞額外參數(shù)例子")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_
())
關(guān)鍵代碼:
from functools import partial
button1.clicked.connect(partial(self.onButtonClick, 1))
button2.clicked.connect(partial(self.onButtonClick, 2))
代碼來源于:書籍 pyqt5快速開發(fā)與實(shí)戰(zhàn)
記錄學(xué)習(xí)筆記
總結(jié)
以上是生活随笔為你收集整理的pyqt5讲解12:自定义参数 (给信号传入参数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。