快捷方式管理(pyqt5升级版) python pytq5

2021-07-10 12:06

阅读:913

标签:行选中   sys.argv   .data   信息   trigger   where   visible   sele   ade   

之前用python写了个小软件http://blog.51cto.com/ikezcn/2142638
说实话用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

标签:行选中   sys.argv   .data   信息   trigger   where   visible   sele   ade   

原文地址:http://blog.51cto.com/ikezcn/2166426


评论


亲,登录后才可以留言!