快捷方式管理(pyqt5升級版) python pytq5
阿新 • • 發佈:2018-08-30
lambda tro wid prim last slot pos qaction int 之前用python寫了個小軟件http://blog.51cto.com/ikezcn/2142638
說實話用tk的話界面確實不好看,所以需要改進,看了pyqt5的介紹想要試一下,對於上次寫的軟件來說這裏只是更改了界面而已。上面的程序不再更新。
說實話用tk的話界面確實不好看,所以需要改進,看了pyqt5的介紹想要試一下,對於上次寫的軟件來說這裏只是更改了界面而已。上面的程序不再更新。
使用的軟件:
python3.6
pyqt5 安裝:pip insatll pyqt5
代碼(幹貨來了,之後會不定時更新):
2018-08-30更新
# -*- coding: utf-8 -*- #v2.0 2018-08-30更新 import sys,os from PyQt5.QtCore import Qt,QVariant from PyQt5.QtSql import QSqlDatabase,QSqlTableModel,QSqlQuery from PyQt5.QtWidgets import QMainWindow,QMessageBox,QHeaderView,QAction, qApp, QApplication, QDesktopWidget , QGridLayout,QTableView,QAbstractItemView from PyQt5.QtGui import QIcon import win32api import win32con class Icon(QMainWindow): def __init__(self,model,sqlite,query,view): super().__init__() self.model = model self.sqlite = sqlite self.query = query self.view = view self.setAcceptDrops(True) self.statusBar().showMessage(‘Reday‘) delAction = QAction("&刪除", self) delAction.setShortcut("Ctrl+D") delAction.setStatusTip("刪除選定的行") delAction.triggered.connect(self.delrow) deltableAction = QAction("&全部刪除", self) deltableAction.setStatusTip("刪除所有的行") deltableAction.triggered.connect(self.deltable) vacuumAction = QAction("&整理數據庫", self) vacuumAction.setShortcut("Ctrl+D") vacuumAction.setStatusTip("讓數據庫變小") vacuumAction.triggered.connect(self.vacuum) menubar = self.menuBar() menubar.addAction(delAction) setMenu = menubar.addMenu(‘&設置‘) setMenu.addAction(vacuumAction) setMenu.addAction(deltableAction) self.table1() QMainWindow.setCentralWidget(self,self.view) self.resize(800, 600) self.center() #居中 self.setWindowTitle("HS快捷方式") #self.setWindowIcon(QIcon("icon.png")) self.show() def delrow(self): if self.model.removeRow(self.view.currentIndex().row()): if not self.model.submitAll(): QMessageBox.information(self,"刪除錯誤",self.model.lastError().text()) def deltable(self): ret = QMessageBox.question(self,"提示!","是否刪除全部路徑",QMessageBox.Ok | QMessageBox.Cancel,QMessageBox.Cancel) if 0x00000400 == ret: #OK self.model.removeRows(0,self.model.rowCount()) self.model.submitAll() def vacuum(self): self.query.exec("VACUUM") def center(self): #窗口居中 #QtGui.QDesktopWidget提供了關於用戶桌面的信息,包括屏幕尺寸。 qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def sql(self): sqlite = QSqlDatabase.addDatabase("QSQLITE") sqlite.setDatabaseName("db") return sqlite def table1(self): try: self.sqlite.open() except (BaseException): QMessageBox.information(self,"程序將關閉","數據庫打開失敗") sys.exit(app.exec_()) self.model.setTable("lj") #self.model.setFilter("isdel = 0") self.model.setSort(1,Qt.AscendingOrder) #按lj列排序 self.model.select() self.model.setHeaderData(0, Qt.Horizontal, "ID") self.model.setHeaderData(1, Qt.Horizontal,"路徑") self.view.setModel(self.model) self.view.setEditTriggers(QAbstractItemView.NoEditTriggers) #禁止對表格編輯 self.view.horizontalHeader().setStretchLastSection(True) #是否填滿寬度 self.view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.view.hideColumn(0)#隱藏列 self.view.hideColumn(2)#隱藏列 self.view.setSelectionBehavior(QAbstractItemView.SelectRows) #點擊整行選中 self.view.setAlternatingRowColors(True) #隔行自動變色 self.view.verticalHeader().setVisible(False)#隱藏表頭 self.view.doubleClicked.connect(lambda:self.slotRowDoubleClicked()) #view.setAcceptDrops(True) self.view.show() def slotRowDoubleClicked(self): try: modedata = self.view.currentIndex().data() data = str(modedata) if os.path.exists(data): win32api.ShellExecute(0,‘open‘,data,‘‘,‘‘,1) else: QMessageBox.information(self,"錯誤!","路徑不存在!") except (BaseException): QMessageBox.information(self,"錯誤!","打開路徑存在錯誤!") #print(sys.exc_info()) #QMessageBox.information(self,"index","index") # def enableBorder(self, enable): # if enable: # self.setStyleSheet("MainWidget{border:3px solid #165E23}") # else: # self.setStyleSheet(‘‘) def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.acceptProposedAction() #self.enableBorder(True) else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls(): event.setDropAction(Qt.LinkAction) event.accept() else: event.ignore() #def dragLeaveEvent(self, event): #print(‘dragLeaveEvent...‘) #self.enableBorder(False) def dropEvent(self, event): if event.mimeData().hasUrls(): counts = -1 record = self.model.record() self.query.prepare("select count(*) as c from lj where lj=?") #不加 as c會報錯 # 遍歷輸出拖動進來的所有文件路徑 for url in event.mimeData().urls(): string = url.toLocalFile().replace(‘/‘,‘\\‘) self.query.bindValue(0,QVariant(string)) if self.query.exec(): while query.next(): counts = query.value(0) if counts > 0: QMessageBox.information(self,"錯誤!","路徑已存在!") elif counts == 0: record.setValue(1,QVariant(url.toLocalFile().replace(‘/‘,‘\\‘))) #lj列 record.setValue(2,QVariant(0)) #isdel列 if self.model.insertRecord(-1,record): self.model.submitAll() elif counts == -1: return event.acceptProposedAction() #self.enableBorder(False) else: event.ignore() def closeEvent(self,event): if self.sqlite.isOpen(): self.sqlite.close() if __name__ == "__main__": #qss = QFile("stylesheet.qss") #樣式表 #qss.open(QIODevice.ReadOnly) #樣式表 app = QApplication(sys.argv) #app.setStyleSheet(str(qss.readAll(),encoding=‘utf-8‘)) #樣式表 #qss.close() #樣式表 sqlite = QSqlDatabase.addDatabase("QSQLITE") sqlite.setDatabaseName("db") model = QSqlTableModel(None,sqlite) model.setEditStrategy(QSqlTableModel.OnManualSubmit) query = QSqlQuery(sqlite) view = QTableView() icon = Icon(model,sqlite,query,view) sys.exit(app.exec_())
樣式表:stylesheet.qss
QTableView { color: black; /*表格內文字顏色*/ gridline-color: white; /*表格內框顏色*/ background-color: rgb(250, 250, 115); alternate-background-color: rgb(141, 163, 215); selection-color: white; /*選中區域的文字顏色*/ selection-background-color: rgb(77, 77, 77); /*選中區域的背景色*/ border: 2px groove gray; border-radius: 0px; padding: 2px 4px; } QHeaderView { color: black; font: bold 10pt; background-color: rgb(108, 108, 108); border: 0px solid rgb(144, 144, 144); border:0px solid rgb(191,191,191); border-left-color: rgba(255, 255, 255, 0); border-top-color: rgba(255, 255, 255, 0); border-radius:0px; min-height:29px; } QHeaderView.section { color: black; background-color: rgb(108, 108, 108); border: 5px solid #f6f7fa; border-radius:0px; border-color: rgb(64, 64, 64); }
數據庫 db
CREATE TABLE lj(id integer primary key,lj text not NULL,isdel BOOLEAN DEFAULT 0)
QT的樣式表使用起來確實很方便,但是覺的打開軟件的時候會變慢所以在代碼裏註釋掉了
說說PYQT5與TK的使用感覺,TK上手方便,拿起來就能寫,PYQT5需要了解它的工作機制所以上手時間會比較長。比較喜歡qss、tableview、tablemodel,qss可以很方便的調整樣式而且和js很像,用過js的上手那叫一個快,tableview與tablemodel聯動可以少些很多代碼,最主要的它的容錯度很高,有些可以不用寫try也不會造成程序停止運行,這點很重要,哈哈,重要的點就在於‘懶’。
快捷方式管理(pyqt5升級版) python pytq5