PyQt - QToolBar Widget



A QToolBar widget is a movable panel consisting of text buttons, buttons with icons or other widgets.

It is usually situated in a horizontal bar below menu bar, although it can be floating. Some useful methods of QToolBar class are as follows −

Sr.No. Methods & Description
1

addAction()

Adds tool buttons having text or icon

2

addSeperator()

Shows tool buttons in groups

3

addWidget()

Adds controls other than button in the toolbar

4

addToolBar()

QMainWindow class method adds a new toolbar

5

setMovable()

Toolbar becomes movable

6

setOrientation()

Toolbar’s orientation sets to Qt.Horizontal or Qt.vertical

Whenever a button on the toolbar is clicked, ActionTriggered() signal is emitted. Additionally, it sends reference to QAction object associated with the event to the connected function.

A File toolbar is added in the toolbar area by calling addToolBar() method.

tb = self.addToolBar("File")

Although tool buttons with text captions can be added, a toolbar usually contains graphic buttons. A QAction object with an icon and name is added to the toolbar.

new = QAction(QIcon("new.bmp"),"new",self)
tb.addAction(new)

Similarly, open and save buttons are added.

Finally, actionTriggered() signal is connected to a slot function toolbtnpressed()

tb.actionTriggered[QAction].connect(self.toolbtnpressed)

The complete code to execute the example is as follows −

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class tooldemo(QMainWindow):
   def __init__(self, parent = None):
      super(tooldemo, self).__init__(parent)
      layout = QVBoxLayout()
      tb = self.addToolBar("File")
		
      new = QAction(QIcon("new.bmp"),"new",self)
      tb.addAction(new)
		
      open = QAction(QIcon("open.bmp"),"open",self)
      tb.addAction(open)
      save = QAction(QIcon("save.bmp"),"save",self)
      tb.addAction(save)
      tb.actionTriggered[QAction].connect(self.toolbtnpressed)
      self.setLayout(layout)
      self.setWindowTitle("toolbar demo")
		
   def toolbtnpressed(self,a):
      print "pressed tool button is",a.text()
		
def main():
   app = QApplication(sys.argv)
   ex = tooldemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()

The above code produces the following output −

QToolBar Widgets Output
Advertisements