日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

pyqt5讲解12:自定义参数 (给信号传入参数)

發(fā)布時間:2024/9/30 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

# -*- coding: utf-8 -*-"""【簡介】部件中的信號槽傳遞,使用lambda表達(dá)式傳參數(shù)示例"""from PyQt5.QtWidgets import QMainWindow, QPushButton, QWidget, QMessageBox, QApplication, QHBoxLayout import sysclass 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ù)

# -*- coding: utf-8 -*-"""【簡介】部件中的信號槽傳遞,使用partial函數(shù)傳參數(shù)示例"""from PyQt5.QtWidgets import QMainWindow, QPushButton, QWidget, QMessageBox, QApplication, QHBoxLayout import sys from functools import partialclass 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)容還不錯,歡迎將生活随笔推薦給好友。