经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
python3+PyQt5 数据库编程--增删改实例
来源:jb51  时间:2019/6/18 8:37:57  对本文有异议

本文通过python3+pyqt5改写实现了python Qt gui 编程变成15章的excise例子。

  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. from PyQt5.QtCore import (QFile, QVariant, Qt)
  5. from PyQt5.QtWidgets import (QApplication, QDialog, QDialogButtonBox, QMenu,
  6. QMessageBox, QTableView, QVBoxLayout)
  7. from PyQt5.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel)
  8.  
  9. MAC = True
  10. try:
  11. from PyQt5.QtGui import qt_mac_set_native_menubar
  12. except ImportError:
  13. MAC = False
  14.  
  15. ID, CATEGORY, SHORTDESC, LONGDESC = range(4)
  16.  
  17.  
  18. class ReferenceDataDlg(QDialog):
  19.  
  20. def __init__(self, parent=None):
  21. super(ReferenceDataDlg, self).__init__(parent)
  22.  
  23. self.model = QSqlTableModel(self)
  24. self.model.setTable("reference")
  25. self.model.setSort(ID, Qt.AscendingOrder)
  26. self.model.setHeaderData(ID, Qt.Horizontal, "ID")
  27. self.model.setHeaderData(CATEGORY, Qt.Horizontal,"Category")
  28. self.model.setHeaderData(SHORTDESC, Qt.Horizontal,"Short Desc.")
  29. self.model.setHeaderData(LONGDESC, Qt.Horizontal,"Long Desc.")
  30. self.model.select()
  31.  
  32. self.view = QTableView()
  33. self.view.setModel(self.model)
  34. self.view.setSelectionMode(QTableView.SingleSelection)
  35. self.view.setSelectionBehavior(QTableView.SelectRows)
  36. self.view.setColumnHidden(ID, True)
  37. self.view.resizeColumnsToContents()
  38.  
  39. buttonBox = QDialogButtonBox()
  40. addButton = buttonBox.addButton("&Add",
  41. QDialogButtonBox.ActionRole)
  42. deleteButton = buttonBox.addButton("&Delete",
  43. QDialogButtonBox.ActionRole)
  44. sortButton = buttonBox.addButton("&Sort",
  45. QDialogButtonBox.ActionRole)
  46. if not MAC:
  47. addButton.setFocusPolicy(Qt.NoFocus)
  48. deleteButton.setFocusPolicy(Qt.NoFocus)
  49. sortButton.setFocusPolicy(Qt.NoFocus)
  50.  
  51. menu = QMenu(self)
  52. sortByCategoryAction = menu.addAction("Sort by &Category")
  53. sortByDescriptionAction = menu.addAction("Sort by &Description")
  54. sortByIDAction = menu.addAction("Sort by &ID")
  55. sortButton.setMenu(menu)
  56. closeButton = buttonBox.addButton(QDialogButtonBox.Close)
  57.  
  58. layout = QVBoxLayout()
  59. layout.addWidget(self.view)
  60. layout.addWidget(buttonBox)
  61. self.setLayout(layout)
  62.  
  63. addButton.clicked.connect(self.addRecord)
  64. deleteButton.clicked.connect(self.deleteRecord)
  65. sortByCategoryAction.triggered.connect(lambda:self.sort(CATEGORY))
  66. sortByDescriptionAction.triggered.connect(lambda:self.sort(SHORTDESC))
  67. sortByIDAction.triggered.connect(lambda:self.sort(ID))
  68. closeButton.clicked.connect(self.accept)
  69. self.setWindowTitle("Reference Data")
  70.  
  71.  
  72. def addRecord(self):
  73. row = self.model.rowCount()
  74. self.model.insertRow(row)
  75. index = self.model.index(row, CATEGORY)
  76. self.view.setCurrentIndex(index)
  77. self.view.edit(index)
  78.  
  79.  
  80. def deleteRecord(self):
  81. index = self.view.currentIndex()
  82. if not index.isValid():
  83. return
  84. record = self.model.record(index.row())
  85. category = record.value(CATEGORY)
  86. desc = record.value(SHORTDESC)
  87. if (QMessageBox.question(self, "Reference Data",
  88. ("Delete {0} from category {1}?"
  89. .format(desc,category)),
  90. QMessageBox.Yes|QMessageBox.No) ==
  91. QMessageBox.No):
  92. return
  93. self.model.removeRow(index.row())
  94. self.model.submitAll()
  95. self.model.select()
  96.  
  97.  
  98. def sort(self, column):
  99. self.model.setSort(column, Qt.AscendingOrder)
  100. self.model.select()
  101.  
  102.  
  103. def main():
  104. app = QApplication(sys.argv)
  105.  
  106. filename = os.path.join(os.path.dirname(__file__), "reference.db")
  107. create = not QFile.exists(filename)
  108.  
  109. db = QSqlDatabase.addDatabase("QSQLITE")
  110. db.setDatabaseName(filename)
  111. if not db.open():
  112. QMessageBox.warning(None, "Reference Data",
  113. "Database Error: {0}".format(db.lastError().text()))
  114. sys.exit(1)
  115.  
  116. if create:
  117. query = QSqlQuery()
  118. query.exec_("""CREATE TABLE reference (
  119. id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,
  120. category VARCHAR(30) NOT NULL,
  121. shortdesc VARCHAR(20) NOT NULL,
  122. longdesc VARCHAR(80))""")
  123.  
  124. form = ReferenceDataDlg()
  125. form.show()
  126. sys.exit(app.exec_())
  127.  
  128. main()

运行结果:

以上这篇python3+PyQt5 数据库编程--增删改实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号