forked from cxinping/PyQt5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqt09_db03.py
67 lines (52 loc) · 1.51 KB
/
qt09_db03.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
'''
【简介】
PyQt5中 处理database 例子
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtSql import QSqlDatabase , QSqlTableModel
from PyQt5.QtCore import Qt
def initializeModel(model):
model.setTable('people')
model.setEditStrategy( QSqlTableModel.OnFieldChange)
model.select()
model.setHeaderData(0, Qt.Horizontal, "ID")
model.setHeaderData(1, Qt.Horizontal, "name")
model.setHeaderData(2, Qt.Horizontal, "address")
def createView(title, model):
view = QTableView()
view.setModel(model)
view.setWindowTitle(title)
return view
def addrow():
ret = model.insertRows( model.rowCount(), 1 )
print( 'insertRows=%s' %str(ret) )
def findrow(i):
delrow= i.row()
print('del row=%s' % str(delrow) )
if __name__ == '__main__':
app = QApplication(sys.argv)
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('./db/database.db')
model = QSqlTableModel()
delrow = -1
initializeModel(model)
view1 = createView("Table Model (View 1)", model)
view1.clicked.connect(findrow)
dlg = QDialog()
layout = QVBoxLayout()
layout.addWidget(view1)
addBtn = QPushButton("添加一行")
addBtn.clicked.connect(addrow)
layout.addWidget(addBtn)
delBtn = QPushButton("删除一行")
delBtn.clicked.connect(lambda: model.removeRow(view1.currentIndex().row()))
layout.addWidget(delBtn)
dlg.setLayout(layout)
dlg.setWindowTitle("Database 例子")
dlg.resize(430, 450)
dlg.show()
sys.exit(app.exec_())