+

PyQt5 QToolButton

Example :

Window with a tool button with an exit icon. When the user clicks this button, the application is closed.

import sys

from PyQt5 import QtCore , QtGui, QtWidgets

 

class Ui_MainWindow ( object ):

def setupUi ( self , MainWindow):

MainWindow.resize ( 506 , 312 )

< p> self . centralwidget = QtWidgets.QWidget (MainWindow)

self . centralwidget.setObjectName ( "centralwidget" )

 

self . toolButton = QtWidgets.QToolButton ( self . centralwidget)

self . toolButton.setGeometry (QtCore.QRect ( 220 , 120 , 41 , 41 ))

 

icon = QtGui.QIcon ()

icon.addPixmap (QtGui.QPixmap ( "exiticon.png [exact location of image]" ),

  QtGui.QIcon.Normal, QtGui.QIcon.Off)

 

# add an icon to the toolbar

self .toolButton.setIcon (icon)

  MainWindow.setCentralWidge t ( self . centralwidget)

 

self . retranslateUi (MainWindow)

QtCore.QMetaObject.connectSlotsByName (MainWindow)

 

# add signal and slot

self . toolButton.clicked.connect ( self . exitapp)

  

def retranslateUi ( self , MainWindow):

  _ translate = QtCore.QCoreApplication.translate

MainWindow.setWindowTitle (_translate ( "MainWindow" , "MainWindow" ))

 

# To close the application

def exitapp ( self ):

sys.exit ()

 

if __ name__ = = "__ main__"

app = QtWidgets.QApplication (sys.argv) 

 

MainWindow = QtWidgets.QMainWindow () 

ui = Ui_MainWindow () 

ui.setupUi (MainWindow) 

  MainWindow.show () 

  sys.exit (app.exec_ ()) 

 

Exit:


When the user clicks this button, the application is closed.

Get Solution for free from DataCamp guru