【发布时间】:2019-03-21 10:20:00
【问题描述】:
我已经做了很多研究,但到目前为止找不到任何有这个特定问题的人。很抱歉,如果已经有一个主题,但找不到它。
我想要做的是在 QGridLayout 中找到一个 QLabel,方法是导入一个 .txt 文件并读出名称和值。
例如:
power 5
现在我需要找到名为 "power_fw" 的 QLabel 来将此标签的文本设置为 "5"
set_value("power 5")
def set_value(talent):
list_value = talent.split(" ") # Now i have a list with talent[0] = "power" and its value at talent[1] = "5"
talent_now = talent[0] + "_fw" # I already have the exact name of the QLabel i am trying to find, which would be "power_fw" at this moment
ui.talent_now.setText(talent[1]) # So the idea is that "talent_now" is a string whichs value is the name of the QLabel i am trying to set a new text. Obviously it does not work, because talent_now is not a QLabel but just its name.
我希望有人可以帮助我解决这个具体问题,如果这个主题已经以某种方式存在,我很抱歉。我找不到任何可行的方法。
在这个问题的上下文中我发现有趣的主题:
get widgets by name from layout
findChild on object created within pyqt designer
这些主题中提供的解决方案都没有让我能够做到这一点。
【问题讨论】:
-
你的意思是
self.ui.findChild(QLabel, talent_now).setText(talent[1])不起作用? -
给我们更多信息。这是类中的常规方法吗?在这种情况下,您将缺少
self作为参数 (def set_value(self, talent):) 和 ui 的实例 (self.ui.talent_now...)。按照您编写的方式,您的函数set_value位于全局范围内(因此期望ui等同于App.ui,或者您决定调用 UI 实例的任何内容)并且您在定义之前调用它。这是您尝试运行代码的方式吗?
标签: python qt pyqt5 qlabel qtwidgets