PyQt:如何动态调用objectNames? [英] PyQt: How to dynamically call objectNames?

查看:951
本文介绍了PyQt:如何动态调用objectNames?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了9个QPushButtons,其中objectName是E1,E2,E3,...,E9。
现在,我想使用从数据库获得的字符串更新他们的文本字段,所以我想做这样的事情:

  query =SELECT evento FROM eventos; 
cur.execute(query)

i = 1
用于在cur中获取
evento = str(fetch)
objectname =E+ str (i)
self.objectname.setText(evento)
i + = 1

此循环获取9行(9字符串)并更新按钮的显示文本。问题是,我必须告诉它哪个按钮要更新,我无法弄清楚如何动态地执行这些行: objectname =E+ str(i) self.objectname.setText(evento)将无法正常工作,因为 AtributeError:'MyWindowClass'对象没有属性'objectname'

解决方案

使用 getattr()

  getattr(self,E + str(i))。setText(evento)


I created 9 QPushButtons which objectName's are E1, E2, E3, ..., E9. Now, I want to update their text field with strings I get from a database, so I want to do something like this:

query="SELECT evento FROM eventos;"
cur.execute(query)

i=1
for fetch in cur:
    evento=str(fetch)
    objectname="E"+str(i)
    self.objectname.setText(evento)
    i+=1

This loops fetches 9 lines (9 strings) and updates the buttons' display text. The problem is that I have to tell it which button to update and I can't figure out how to do it dynamically since the lines: objectname="E"+str(i) and self.objectname.setText(evento) won't work because AtributeError: 'MyWindowClass' object has no attribute 'objectname'

解决方案

Use getattr():

getattr(self, "E"+str(i)).setText(evento)

这篇关于PyQt:如何动态调用objectNames?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆