本文介绍了PyQT 按钮点击名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 pyQT 的 gridLayout 中动态创建了按钮(QtoolButton).如何获取在布局中单击的按钮的名称?

I have dynamically created buttons(QtoolButton) in gridLayout in pyQT.How can I get the name of the button clicked in the layout?

我一开始不知道名字.是否有任何触发来完成任务?

I can't know the name before hand.Is there is any trigger to accomplish the task?

提前致谢.

推荐答案

您可以在连接到按钮事件的函数中调用 self.sender() 来获取触发事件的对象.从那里你可以调用对象的 objectName() 方法来获取名称.

You can call self.sender() in a function connected to your button event to get the object that triggered the event. From there you can call the object's objectName() method to get the name.

这是一个简单的示例 - 小部件有 10 个按钮,单击按钮将更新标签文本以显示按钮名称.

Here's a quick example - the widget has 10 buttons and clicking on a button will update the label's text to show the button name.

import sys
from PyQt4.QtGui import QApplication, QWidget, QToolButton, QLabel, QVBoxLayout, QHBoxLayout

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.button_layout = QHBoxLayout()
        self.widget_layout = QVBoxLayout()

        for button_number in xrange(1, 11):
            button = QToolButton()
            button.setText(str(button_number))
            button.setObjectName('Button%d' % button_number)
            button.released.connect(self.button_released)
            self.button_layout.addWidget(button)

        self.status_label = QLabel('No button clicked')

        self.widget_layout.addItem(self.button_layout)
        self.widget_layout.addWidget(self.status_label)
        self.setLayout(self.widget_layout)

    def button_released(self):
        sending_button = self.sender()
        self.status_label.setText('%s Clicked!' % str(sending_button.objectName()))




if __name__ == '__main__':
  app = QApplication(sys.argv)

  widget = Widget()
  widget.show()

  sys.exit(app.exec_())

这篇关于PyQT 按钮点击名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:03