【问题标题】:PyQt5 setText by object name?PyQt5 setText 按对象名称?
【发布时间】:2017-06-30 16:35:02
【问题描述】:

我有一个按钮网格,每个按钮都位于它自己的组框内。我想动态更新这些按钮的标签。

我不清楚在迭代中创建这些按钮后如何处理这些按钮,有没有办法只处理它们的对象名称。

我阅读的文档似乎没有包含任何通过对象名称设置文本的方法。这是可能的还是有更好的方法来做到这一点?

PyQt5,Python 3.6

【问题讨论】:

  • @ekhumoro。我不确定你的建议是什么。我的每个按钮都在 QGroupBox 内,作为在每个按钮上方添加紧密标签的一种方式。我还希望更改单个框的背景颜色以响应事件(不更改按钮本身的颜色,因为我也希望将其作为不同事件的指示器)。我可以像实际按钮小部件一样为 QGroupBoxes 分配一个整数 id 吗?目前它们已添加到 QGridLayout。
  • 每个按钮都将其组框作为父级,因此您可以使用button.parent() 访问它。按钮组提供了一种统一的方式来访问一组按钮(使用 id)并通过单个连接处理它们的所有信号。这只是一个简单的便利类,让您不必自己管理按钮。 (PS:你也可以use Qt Designer to set up button-groups)。

标签: python python-3.x pyqt pyqt5


【解决方案1】:

如果您已使用该功能为小部件命名:

your_widget.setObjectName(your_name)

您可以通过findChild函数通过父级访问它:

your_parent_widget.findChild(name_class, your_name)

例子:

import sys

from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget


class Widget(QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent=parent)
        self.verticalLayout = QVBoxLayout(self)
        # self.verticalLayout.setObjectName("verticalLayout")
        for i in range(10):
            pushButton = QPushButton(self)
            pushButton.setObjectName("pushButton{}".format(i))
            pushButton.setText(str(i))
            self.verticalLayout.addWidget(pushButton)

        timer = QTimer(self)
        timer.setInterval(1000)
        timer.timeout.connect(self.updateText)
        timer.start()

    def updateText(self):
        for i in range(10):
            child = self.findChild(QPushButton, "pushButton{}".format(i))
            counter = int(child.text())
            child.setText(str(counter+1))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 2014-01-16
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多