【PyQt5】{12} —— 連接帶參數的槽函數

連接帶參數的槽函數,必須傳入一個函數對象,而不是函數的調用結果,因此使用lambda把函數封裝成函數對象。
# -*- coding: utf-8 -*-
"""
Created on Sat May  9 12:16:58 2020

@author: Giyn
"""

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout


class Simple_Window(QWidget):
    def __init__(self):
        super(Simple_Window, self).__init__() # 使用super函數可以實現子類使用父類的方法
        self.label = QLabel("I am the original Label", self) # self是指定的父類Simple_Window,表示QLabel屬於Simple_Window窗口
        self.button = QPushButton("Button", self)
        
        self.button.clicked.connect(lambda: self.change_label("I am the changed Label")) # 此處要使用匿名函數把函數封裝成函數對象
        
        self.v_layout = QVBoxLayout() # 實例化一個QVBoxLayout對象
        self.v_layout.addWidget(self.label)
        self.v_layout.addWidget(self.button)
        
        self.setLayout(self.v_layout) # 調用窗口的setLayout方法將總佈局設置爲窗口的整體佈局
        
    def change_label(self, text):
        self.label.setText(text)
        
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Simple_Window()
    window.show()
    sys.exit(app.exec())

Output:

When not clicked:

在這裏插入圖片描述

When clicked:

在這裏插入圖片描述


Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818

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