6.添加动作

在主窗口基础之上,添加菜单和工具栏等的动作。
// !!! Qt 5
// ========== mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
 
private:
    void open();
 
    QAction *openAction;
};
 
#endif // MAINWINDOW_H
 
// ========== mainwindow.cpp
#include <QAction>
#include <QMenuBar>
#include <QMessageBox>
#include <QStatusBar>
#include <QToolBar>
 
#include "mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setWindowTitle(tr("Main Window"));
 
    openAction = new QAction(QIcon(":/images/doc-open"), tr("&Open..."), this);
    openAction->setShortcuts(QKeySequence::Open);
    openAction->setStatusTip(tr("Open an existing file"));
    connect(openAction, &QAction::triggered, this, &MainWindow::open);
 
    QMenu *file = menuBar()->addMenu(tr("&File"));
    file->addAction(openAction);
 
    QToolBar *toolBar = addToolBar(tr("&File"));
    toolBar->addAction(openAction);
 
    statusBar() ;
}
 
MainWindow::~MainWindow()
{
}
 
void MainWindow::open()
{
    QMessageBox::information(this, tr("Information"), tr("Open"));
}


int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
 
    MainWindow win;
    win.show();
 
    return app.exec();
}

 

posted @ 2018-07-17 22:06  LyndonMario  阅读(229)  评论(0编辑  收藏  举报