首页 > 解决方案 > 如何动态定义窗口名称变量

问题描述

我需要将窗口 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()

标签: pythonvariablespyqt

解决方案


纯粹的技术答案是您想要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"


推荐阅读