Qt Qaction Example

Simple example that shows how a QAction can be used in a QMenu, QToolBar and in a keyboard shortcut.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
namespace Ui {
    class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
 
private:
    Ui::MainWindow *ui;
 
private slots:
    void open();
};
 
#endif // MAINWINDOW_H

mainwindow.cpp

#include <QtGui>
 
#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
 
    QMenu *menuFile = new QMenu("&File");
 
    //Abstract user interface action that can be inserted into widgets.
    //In this example, actionOpen is inserted into the QMenu file.
    QAction *actionOpen;
    actionOpen = new QAction("&Open", this);
 
    //add keyboard shortcut. This is usually CTRL+O
    actionOpen->setShortcut(QKeySequence::Open);
    menuFile->addAction(actionOpen);
 
    menuBar()->addMenu(menuFile);
 
    //create a toolBart
    QToolBar *toolBarFile = addToolBar("File");
    //add the same action in the toolbar.
    toolBarFile->addAction(actionOpen);
 
    //connect this action to the slot open()
    connect(actionOpen, SIGNAL(triggered()), this, SLOT(open()));
 
}
 
void MainWindow::open()
{
     statusBar()->showMessage(tr("File Opened"),2000);
}
 
MainWindow::~MainWindow()
{
    delete ui;
}

mainwindow.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>400</width>
    <height>300</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget"/>
  <widget class="QMenuBar" name="menuBar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>400</width>
     <height>23</height>
    </rect>
   </property>
  </widget>
  <widget class="QToolBar" name="mainToolBar">
   <attribute name="toolBarArea">
    <enum>TopToolBarArea</enum>
   </attribute>
   <attribute name="toolBarBreak">
    <bool>false</bool>
   </attribute>
  </widget>
  <widget class="QStatusBar" name="statusBar"/>
 </widget>
 <layoutdefault spacing="6" margin="11"/>
 <resources/>
 <connections/>
</ui>

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
 
    return a.exec();
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.