python - 如何动态定义窗口名称变量
问题描述
我需要将窗口 id 放在窗口变量名中。
我需要使用坐标表动态创建几个窗口,并能够引用它们中的每一个。当我从下面使用此代码时,我只能调用最后制作的窗口。我试图以这种方式定义窗口:
getattr(self, "tb_points%i" % i) = QtGui.QMainWindow()
但这给了我一个错误:
SyntaxError: can't assign to function call
代码:
import sqlite3
conn = sqlite3.connect('database.db')
tables = conn.execute("select id from points group by table_id").fetchall()
for i in range(len(tables)):
tab_id = unicode(tables[i][0])
q = conn.execute("select * from points where tab_id='"+tab_id+"'").fetchall()
self.tb_points = QtGui.QMainWindow()
self.tv_points = QtGui.QTableView()
self.tv_model = QtGui.QStandardItemModel(len(q), 7, self)
我希望能够调用,例如:
self.tv_points5.setModel(self.tv_model5)
self.tb_points5.show()
self.tb_points3.hide()
解决方案
纯粹的技术答案是您想要setattr(obj, name, value)
:
setattr(self, "tb_points%i" % i, QtGui.QMainWindow())
但这是一个众所周知的反模式(您将如何使用您不知道名称的属性?),因此正确的设计是使用列表或字典,即:
self.dyn_windows = []
# unrelated : python "for" loops are of the "foreach" kind
for tab_id in tables:
# ...
# for each tab_id, we store a dict referencing the three related windows
self.dyn_windows.append({
"tb_points": QtGui.QMainWindow(),
"tv_points": QtGui.QTableView(),
"tv_model": QtGui.QStandardItemModel(len(q), 7, self)
})
也(不相关但),
1/ db-api 的正确使用是:
cursor = conn.cursor()
# nb: the exact placeholder depends on your db vendor
cursor.execute("select * from xxxx where tab_id=%", [tab_id])
2/如果不知道您的数据库架构以及您到底想要做什么,我无法给出一个工作示例,但是如果您想要的是“table_id”列表(或者这是“tab_id”???):数字点数”,使用聚合肯定有更好的方法,即"select tab_id, count(*) from points group by tab_id"
推荐阅读
- mysql - MySQL)如何删除使用 WHILE 循环的重复行?
- dc.js - 条形图显示线条(细条)而不是条 [已解决]
- java - 如何在 Android 内部保存流式传感器数据?
- java - 如何使用 Spring Integration 在 IntegrationFlow 链中通过 SFTP 上传文件?
- python - 在 Windows 上,导入 CV2 时 DLL 加载失败:找不到指定的模块
- python - 部署 Django 应用程序(Apache、Passenger、Virtualenv)
- django - Django:如何在不刷新页面的情况下在提交第一个表单时显示第二个表单?
- neo4j - MLM 图的递归密码查询
- swift - 如何修复UIKit中从底部切割的字体?
- c# - 我的播放器预制件向前移动,直到它撞到一个物体,这是怎么回事?