Reputation: 183
I need to put window id in window variable name.
I need to dynamically create few windows with the coordinates tables and be able to refer to each of them. When I use this code from below I can only call the last made window. I tried to define windows this way:
getattr(self, "tb_points%i" % i) = QtGui.QMainWindow()
But it gives me an error:
SyntaxError: can't assign to function call
code:
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)
I want to be able to call, for example:
self.tv_points5.setModel(self.tv_model5)
self.tb_points5.show()
self.tb_points3.hide()
Upvotes: 1
Views: 109
Reputation: 77912
The purely technical answer is that you want setattr(obj, name, value)
:
setattr(self, "tb_points%i" % i, QtGui.QMainWindow())
but that's a well known antipattern (how are you going to use attributes that you don't know the name of ?), so a proper design would be to use a list or a dict, ie:
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)
})
Also (unrelated but),
1/ the proper use of the db-api is:
cursor = conn.cursor()
# nb: the exact placeholder depends on your db vendor
cursor.execute("select * from xxxx where tab_id=%", [tab_id])
2/ I can't get give a working example without knowing your db schema and what exactly you're trying to to but if what you want is a list of "table_id" (or is this "tab_id" ???) : number of points", there's certainly a much better way using aggregations, ie "select tab_id, count(*) from points group by tab_id"
Upvotes: 1