Create a button with a three-state background picture
Class Pussbutton: # # Generate a button with a tri-state background picture # DEF init (self, *imgpath): From pyqt5.qtwidgets import QP Ushbutton from Pyqt5.qtgui import qpixmap length = Len (Imgpath) If Length==3:nomalpath = imgpath[0] Hoverpath = imgpath[1] Pressedpath = img PATH[2] Else:pressedpath=hoverpath=nomalpath = imgpath[0] Pixmap_mask=qp Ixmap ('./img/1.png ') but = Qpushbutton (") Print (' Pressedpath ', Pressedpath,imgpath) #调整按钮的大小, making it consistent with the size of the background but.setfixedsize (Pixmap_mask.width (), Pixmap_mask.height ()) # Three states of the picture But.setstylesheet ("Qpushbutton{border-image:url" ("+nomalpath+");} " "Qpushbutton:hover{border-image:url (" +hoverpath+ ");}" "Qpushbutton:pressed{border-image:url (" +pressedpath+ ");}") # # Set Matte, if not set matte, the white part of PNG picture can also click on the # But.setmask (Pixmap_mask.createheuristicmask ()) return but Def init2 (self): from pyqt5.qtwidgets import Qpushbutton From Pyqt5.qtgui import Qpixmap, Qicon from pyqt5.qtcore import qsize Pixmap_mask=qpixmap ('./img/1.png ') but = Qpushbutton (") But.setfixedsize (Pixmap_mask.width (), Pixmap_mask.height ()); But.setmask (Pixmap_mask.createheuristicmask ()); icon = Qicon (pixmap_mask) But.seticon (icon); But.seticonsize (Qsize (Pixmap_mask.width (), Pixmap_mask.height ()); But.settooltip ("Hello") but.clicked.connect (Self.print_click) return but def print_click (self): print (' Print_click ') if __name__ = = ' __main__ ': impo RT SYS from PyQt5.qtwidgets Import qapplication from pyqt5.qtwidgets import (Qwidget, Qlabel, qvboxlayout) from Pyqt5.qtcore im Port Qt from Pyqt5.qtgui import qpixmap, qimage app = Qapplication (SYS.ARGV) ################# #################################### main= qwidget () Layout_main = Qvboxlayout () layout_main.setalignm ENT (qt.alignleft) main.setlayout (layout_main) label _top = Qlabel () pixmap_top=qpixmap ('./img/3.png ') Label_top.setpixmap (pixmap_top) layout_main.addwidget (label_top Tool = Pussbutton () paths = ['./img/1.png ', './img/2.png ', './img/3.png '] but_3 = Tool.init (*paths) layou T_main.addwidget (but_3) but_4 =tool.init2 () layout_main.addwidget (but_4) image = Qimage ("./img/2.png" ); pixmap= Qpixmap () pixmap.convertfromimage (image) label= Qlabel () label.setpixmap (pixmap) main.show () ##### ################################################ Sys.exit (APP.EXEC_ ())
Create a button with a three-state background picture