Shortcut management (PYQT5 upgrade) Python Pytq5

Source: Internet
Author: User

Before, I wrote a little software in Python http://blog.51cto.com/ikezcn/2142638
To tell the truth with TK words interface is really not good to see, so need to improve, see the introduction of Pyqt5 want to try, for the last written software here just changed the interface. The above program is no longer updated.

The software used:
python3.6
PYQT5 installation: Pip insatll pyqt5

The code (dry goods come, then will not update regularly):
2018-08-30 Update

#-*-Coding:utf-8-*-#v2.0 2018-08-30 Update import sys,osfrom pyqt5.qtcore import qt,qvariantfrom pyqt5.qtsql import Qsqldata Base,qsqltablemodel,qsqlqueryfrom pyqt5.qtwidgets Import qmainwindow,qmessagebox,qheaderview,qaction, qApp, Qapplication, Qdesktopwidget, qgridlayout,qtableview,qabstractitemviewfrom Pyqt5.qtgui import QIconimport        Win32apiimport win32conclass Icon (qmainwindow): def __init__ (Self,model,sqlite,query,view): Super (). __INIT__ () Self.model = Model Self.sqlite = SQLite self.query = Query Self.view = view Self.setacce Ptdrops (True) Self.statusbar (). ShowMessage (' reday ') delaction = Qaction ("& Delete", self) delaction.se Tshortcut ("Ctrl+d") delaction.setstatustip ("Delete selected rows") DelAction.triggered.connect (Self.delrow) deltabl Eaction = Qaction ("& Delete all", self) deltableaction.setstatustip ("Delete all Rows") DeltableAction.triggered.connect ( self.deltable) vacuumaction = Qaction ("& FinishingDatabase ", self) vacuumaction.setshortcut (" Ctrl+d ") Vacuumaction.setstatustip (" Make database smaller ") Vacuumaction.trigg Ered.connect (self.vacuum) menubar = Self.menubar () menubar.addaction (delaction) SetMenu = Menubar.add        Menu (' & Settings ') setmenu.addaction (vacuumaction) setmenu.addaction (deltableaction) self.table1 () Qmainwindow.setcentralwidget (Self,self.view) self.resize (+) Self.center () #居中 Self.setwindow Title ("HS shortcut") #self. Setwindowicon (Qicon ("Icon.png")) Self.show () def delrow (self): if Self.model . Removerow (Self.view.currentIndex (). Row ()): If not Self.model.submitAll (): Qmessagebox.informati On (self, "delete error", Self.model.lastError (). Text ()) def deltable (self): ret = qmessagebox.question (self, "prompt!", "whether to remove all paths Path ", Qmessagebox.ok | Qmessagebox.cancel,qmessagebox.cancel) If 0x00000400 = = ret: #OK self.model.removeRows (0,SELF.MODEL.ROWC Ount()) Self.model.submitAll () def vacuum (self): self.query.exec ("vacuum") def Center (self): #窗口居中        #QtGui. Qdesktopwidget provides information about the user's desktop, including the screen size. qr = Self.framegeometry () CP = Qdesktopwidget (). Availablegeometry (). Center () qr.movecenter (CP) SELF.M Ove (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, "program closes", "Database Open Failed") 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, "path") self . View.setmodel (Self.model) self.view.setEditTriggers (qabstractitemview.noedittriggers) #禁止对表格编辑 Self.view.horizontalHeader (). Setstretchlastsection (True) #是否填满宽度 Self.view.horizontalHeader (). Sets Ectionresizemode (qheaderview.stretch) self.view.hideColumn (0) #隐藏列 Self.view.hideColumn (2) #隐藏列 SELF.VI        Ew.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.ex Ists (data): Win32API. ShellExecute (0, ' open ', data, ', ', ' 1 ') else:QMessageBox.information (self, "Error!)        "," path does not exist! ") Except (baseexception): Qmessagebox.information (self, "Error!            "," There is an error in the Open path! ") #print (Sys.exc_info ()) #QMessageBox. Information (self, "index", "Index") # def enableborder (self, enable): # If enable: # Self.setstyleshee T ("mainwidget{border:3px Solid #165E23}") # Else: # Self.setstylesheet (') def dragenterevent (self, E        VENT): 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): I F Event.mimedata (). Hasurls (): counts = 1 record = Self.model.record () self.query.prepare ("SELECT count (*) as C from LJ where lj=?")               #不加 as C will error # traverse the output to drag all the file paths that come in for the URL in Event.mimedata (). URLs (): string = Url.tolocalfile (). Replace ('/', ' \ \ ') Self.query.bindValue (0,qvariant (string)) if SE Lf.query.exec (): While Query.next (): counts = Query.value (0) if C Ounts > 0:qmessagebox.information (self, "Error! "," The path already exists! ") elif counts = = 0:record.setvalue (1,qvariant (Url.tolocalfile (). Replace ('/', ' \ \ '))) #                        LJ Column Record.setvalue (2,qvariant (0)) #isdel列 if Self.model.insertRecord ( -1,record): Self.model.submitAll () elif counts = = -1:return EVENT.A Cceptproposedaction () #self. Enableborder (False) else:event.ignore () def closeevent (self,e VENT): If Self.sqlite.isOpen (): Self.sqlite.close () if __name__ = = "__main__": #qss = QFile ("Styleshee T.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 (QS    Qltablemodel.onmanualsubmit) query = Qsqlquery (sqlite) view = Qtableview () icon = icon (Model,sqlite,query,view) Sys.exit (App.exec_ ())

Style sheet: 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);}

Database db

CREATE TABLE lj(id integer primary key,lj text not NULL,isdel BOOLEAN DEFAULT 0)

QT style sheets are really handy to use, but when you open the software it slows down and it's commented out in the code.

Talk about the use of PYQT5 and Tk feel, TK Handy, pick up can write, PYQT5 need to understand its working mechanism so the start time will be relatively long. Compared to like QSS, TableView, TABLEMODEL,QSS can be very convenient to adjust the style and JS very much like, with JS to get started that called a fast, TableView and TableModel linkage can be less a lot of code, the main fault tolerance is very high, Some can not write try and will not cause the program to stop running, this is very important, haha, the important point is ' lazy '.

Shortcut management (PYQT5 upgrade) Python Pytq5

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.