python - 如何知道 QButtonGroup 中按下了哪个按钮?
问题描述
我有一个函数可以创建一个框架并在其中放置一个行编辑和一个按钮,然后将按钮放置在 QButtonGroup 上:
self.btn_group = QButtonGroup(self.ui_main.scrollArea_content)
def new(self):
# Create the frame
self.ui_main.frame_content = QFrame(self.ui_main.scrollArea_content)
self.ui_main.frame_content.setObjectName(f"frame_content_{self.counter}")
self.ui_main.frame_content.setMaximumSize(QSize(16777215, 70))
self.ui_main.frame_content.setFrameShape(QFrame.StyledPanel)
self.ui_main.frame_content.setFrameShadow(QFrame.Raised)
# Create horizontal layout
self.ui_main.horizontalLayout_4 = QHBoxLayout(self.ui_main.frame_content)
self.ui_main.horizontalLayout_4.setObjectName(f"horizontalLayout_4_{self.counter}")
# Create line edit content
self.ui_main.line_content = QLineEdit(self.ui_main.frame_content)
self.ui_main.line_content.setObjectName(f"line_content_{self.counter}")
# Add line edit content to horizontal layout
self.ui_main.horizontalLayout_4.addWidget(self.ui_main.line_content)
# Create the button remove
self.ui_main.btn_remove = QPushButton(self.ui_main.frame_content)
self.ui_main.btn_remove.setObjectName(f"btn_remove_{self.counter}")
self.ui_main.btn_remove.setMinimumSize(QSize(0, 50))
self.ui_main.btn_remove.setMaximumSize(QSize(80, 16777215))
self.ui_main.btn_remove.setText(u"Remove")
# Add button remove to horizontal layout
self.ui_main.horizontalLayout_4.addWidget(self.ui_main.btn_remove)
# Add the frame content(contains line edit and button) to vertical layout
self.ui_main.verticalLayout_3.addWidget(self.ui_main.frame_content, 0, Qt.AlignTop)
# Add button to group
self.btn_group.addButton(self.ui_main.btn_remove)
# Increment the counter to name the next button
self.counter += 1
之后,我连接到按钮组以初始化删除功能,这将删除包含行编辑和按钮的整个框架
self.btn_group.buttonClicked.connect(self.remove)
但是对于按钮组,我只能知道是否单击了任何按钮,而不是单击了哪个按钮,buttonClicked 方法返回一个按钮组对象,其中不包含有关单击的按钮的任何内容,有一种方法可以知道在 QButtonGroup 中按下了哪个按钮? 如果不是我怎么能解决这个问题?
解决方案
buttonClicked
信号发送被点击的按钮:
def remove(self, button):
print(button, button.text())
演示:
from PyQt5 import QtWidgets
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
view = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(view)
group = QtWidgets.QButtonGroup()
for i in range(5):
button = QtWidgets.QPushButton(f"button-{i}")
lay.addWidget(button)
group.addButton(button)
view.show()
def handle_button_clicked(button):
print(button, button.text())
group.buttonClicked.connect(handle_button_clicked)
sys.exit(app.exec_())
推荐阅读
- wso2 - 如何让用户使用他们的电子邮件地址登录?
- prolog - 有人可以解释一下 Prolog 列表中嵌套对的含义吗?
- mips - MIPS 架构执行称为交换的指令
- .net - vb.net 如何以与文件资源管理器>名称降序相同的反向字母数字顺序列出目录中的文件集合
- angular - Angular 6 将表单发布到新标签
- node.js - 未知的 npm install 语法与 gulp
- python - 使用 vtk 从深度图图像生成点云
- python - Jupyter 在虚拟环境中运行终端,但在基础 python 中运行 ipynb
- javascript - 操作 DOM 节点
- r - Base R - 函数一般问题 - 输出具有输入名称的变量