python - PyQt5 setText 按对象名称?

标签 python python-3.x pyqt pyqt5

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

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

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

PyQt5、Python 3.6

最佳答案

如果您使用以下函数为小部件命名:

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_())

关于python - PyQt5 setText 按对象名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42191391/

相关文章:

python - 列出给定类的层次结构中的所有基类?

python - 类型错误 : can't use a string pattern on a bytes-like object

python - 使用 Pandas 操作数据框,创建新列并根据在数据框中查找现有数据来填充它们的值

python-3.x - 使用文件夹结构迭代 S3 存储桶中的文件

python - 如何将 QPixmap 的图像转换为字节

Python PyQt4 无效语法

python - ModuleNotFoundError : No module named 'DEGNet' while attempting >Python manage. py makemigrations|python 3.7,django 2.1.7

python - Spark模型保存到pyspark后对操作系统不可见

python - 使用 geopy 将英里转换为纬度和经度

python - IDLE无法找到PyQt5安装