PyQt5 QCommandLinkButton – 删除动作对象

  • Post category:Python

当需要在 PyQt5 应用程序中使用具有按键样式的超链接时,我们可以使用 QCommandLinkButton 。删除动作对象是 QCommandLinkButton 的其中一个动作对象。本篇文章将详细介绍如何在 PyQt5 应用程序中使用 QCommandLinkButton ,以及如何使用“删除动作对象”。

使用 QCommandLinkButton

QCommandLinkButton 是 PyQt5 的一个子类,可以用于创建按键样式的超链接,常用于创建提示信息、帮助文档等。

  1. 创建 QCommandLinkButton

在代码中,我们可以使用以下语句创建 QCommandLinkButton :

button = QtWidgets.QCommandLinkButton("文本", parent)

其中参数 “文本” 表示超链接文本, parent 表示该控件的父控件。

  1. 设置 QCommandLinkButton 的数据

设置 QCommandLinkButton 的数据也很简单,我们可以使用以下方法:

button.setDescription("描述")  # 设置描述
button.setIcon(QtGui.QIcon("路径"))  # 设置图标

图标可以是任何格式的图像文件,路径必须是图像文件的本地路径。

  1. 响应 QCommandLinkButton 的点击事件

我们可以通过以下方法,响应 QCommandLinkButton 的点击事件:

button.clicked.connect(method)

其中, method 表示 QCommandLinkButton 被点击时的回调方法,可以是一个函数或一个 lambda 表达式。

删除动作对象

在 PyQt5 应用程序中,我们可以删除动作对象来清空 QCommandLinkButton 。 其中,动作对象是一组在 QCommandLinkButton 上附加的对象(例如,图标,文本,还有一个处理方法),使用以下语句可以删除动作对象:

button.clear()

我们来看一个例子:

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Example(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        button = QtWidgets.QCommandLinkButton("删除", self)
        button.clicked.connect(self.clear_button)
        button.move(20, 20)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle("Demo")

    def clear_button(self):
        button.clear()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

以上代码将创建一个名为“ Demo”的 PyQT5 应用程序,该应用程序包含一个 QCommandLinkButton ,当 QCommandLinkButton 被触发时,它将呼叫方法 clear_button() ,该方法将删除 QCommandLinkButton 的所有动作对象。

我们再来看一个例子,这里我们将示例的 QCommandLinkButton 增加一个“添加”按钮,当我们点击“添加”按钮后,会创建新的 QCommandLinkButton 控件。

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Example(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.addButton = QtWidgets.QPushButton("添加", self)
        self.addButton.clicked.connect(self.add_button)

        self.button = QtWidgets.QCommandLinkButton("删除", self)
        self.button.clicked.connect(self.clear_button)
        self.button.move(20, 20)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle("Demo")

    def add_button(self):
        button = QtWidgets.QCommandLinkButton("删除", self)
        button.clicked.connect(self.clear_button)
        button.move(20, 20 + len(self.findChildren(QtWidgets.QCommandLinkButton)) * 70)

    def clear_button(self):
        self.sender().clear()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

在此示例中,我们增加了一个“添加”按钮,当我们点击“添加”按钮时,新创建一个 QCommandLinkButton 控件,并可以随时点击删除。