python3+PyQt5 数据库编程数据库编程--增删改实例增删改实例
今天小编就为大家分享一篇python3+PyQt5 数据库编程--增删改实例,具有很好的参考价值,希望对大家有所帮
助。一起跟随小编过来看看吧
本文通过python3+pyqt5改写实现了python Qt gui 编程变成15章的excise例子。
#!/usr/bin/env python3
import os
import sys
from PyQt5.QtCore import (QFile, QVariant, Qt)
from PyQt5.QtWidgets import (QApplication, QDialog, QDialogButtonBox, QMenu,
QMessageBox, QTableView, QVBoxLayout)
from PyQt5.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel)
MAC = True
try:
from PyQt5.QtGui import qt_mac_set_native_menubar
except ImportError:
MAC = False
ID, CATEGORY, SHORTDESC, LONGDESC = range(4)
class ReferenceDataDlg(QDialog):
def __init__(self, parent=None):
super(ReferenceDataDlg, self).__init__(parent)
self.model = QSqlTableModel(self)
self.model.setTable("reference")
self.model.setSort(ID, Qt.AscendingOrder)
self.model.setHeaderData(ID, Qt.Horizontal, "ID")
self.model.setHeaderData(CATEGORY, Qt.Horizontal,"Category")
self.model.setHeaderData(SHORTDESC, Qt.Horizontal,"Short Desc.")
self.model.setHeaderData(LONGDESC, Qt.Horizontal,"Long Desc.")
self.model.select()
self.view = QTableView()
self.view.setModel(self.model)
self.view.setSelectionMode(QTableView.SingleSelection)
self.view.setSelectionBehavior(QTableView.SelectRows)
self.view.setColumnHidden(ID, True)
self.view.resizeColumnsToContents()
buttonBox = QDialogButtonBox()
addButton = buttonBox.addButton("&Add",
QDialogButtonBox.ActionRole)
deleteButton = buttonBox.addButton("&Delete",
QDialogButtonBox.ActionRole)
sortButton = buttonBox.addButton("&Sort",
QDialogButtonBox.ActionRole)
if not MAC:
addButton.setFocusPolicy(Qt.NoFocus)
deleteButton.setFocusPolicy(Qt.NoFocus)
sortButton.setFocusPolicy(Qt.NoFocus)
menu = QMenu(self)
sortByCategoryAction = menu.addAction("Sort by &Category")
sortByDescriptionAction = menu.addAction("Sort by &Description")
sortByIDAction = menu.addAction("Sort by &ID")
sortButton.setMenu(menu)
closeButton = buttonBox.addButton(QDialogButtonBox.Close)
layout = QVBoxLayout()
layout.addWidget(self.view)
layout.addWidget(buttonBox)
self.setLayout(layout)
addButton.clicked.connect(self.addRecord)
deleteButton.clicked.connect(self.deleteRecord)
sortByCategoryAction.triggered.connect(lambda:self.sort(CATEGORY))
sortByDescriptionAction.triggered.connect(lambda:self.sort(SHORTDESC))
sortByIDAction.triggered.connect(lambda:self.sort(ID))
closeButton.clicked.connect(self.accept)
self.setWindowTitle("Reference Data")
def addRecord(self):
评论0
最新资源