大阪市中央区 システムソフトウェア開発会社

営業時間:平日09:15〜18:15
MENU

Qtプログラミング – メニュー、アクションを作成

株式会社クローバーフィールドの経営理念
著者:津路高広
公開日:2019/09/19
最終更新日:2019/09/19
カテゴリー:技術情報

津路です。
今回は、前回より一歩進めて、メニューやステータスバー、メニューに伴うアクションを作成します。
1.アクション
アクションとは、メニューやツールバーに追加して、表示する項目です。
例えば、ヘルプメニューをクリックすると、AboutとAboutQtという項目が表示され、それぞれにツールチップを表示しようとすると、以下のようにアクションを作成します。

void MainWindow::createActions()
{
    aboutAction = new QAction(tr("&About"),this);
    aboutAction->setStatusTip(tr("Show About box"));
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
    aboutQtAction = new QAction(tr("About &Qt"),this);
    aboutQtAction->setStatusTip(tr("Show the Qt library About box"));
    connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
}

上記connectメソッドで、アクションに対するスロットを登録します。
2.メニュー
上記の例では、以下のようにコーディングします。

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    editMenu = menuBar()->addMenu(tr("&Edit"));
    selectMenu = menuBar()->addMenu(tr("&Select"));
    editMenu->addSeparator();
    menuBar()->addSeparator();
    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAction);
    helpMenu->addAction(aboutQtAction);
}

File,Edit, Selectメニューに対するアクションなどは、実装されていません。
3.ステータスバー
以下のように、メニュー項目に対するツールチップなどを表示するため、ステータスバーを作成しておきます。

void MainWindow::createStatusBar()
{
    locationLabel = new QLabel(" W999 ");
    locationLabel->setAlignment(Qt::AlignHCenter);
    locationLabel->setMinimumSize(locationLabel->sizeHint());

    formulaLabel = new QLabel;
    formulaLabel->setIndent(3);

    statusBar()->addWidget(locationLabel);
    statusBar()->addWidget(formulaLabel,1);
}

4.メニュー項目 About
2.で、Helpメニュー下に、Aboutを追加しました。
そして、connectメソッドにて、about関数をスロットとして登録しました。
about関数では、以下のように、htmlコーディングできます。

void MainWindow::about()
{
    QMessageBox::about(this, tr("About Spreadsheet"),
        tr("<h2>Spreadsheet 1.0</h2>"
	   "<p>Copyright &copy; 2019 Cloverfield Inc."
	   "<p>Spreadsheet is a small app that "
	   "demonstrates <b>QAction</b>, <b>QMainWindow</b>, "
	   "<b>QMenuBar</b>, etc,"));
}

以上のソースのほかに、main.cpp, mainwindow.hを作成して、Makefileにてmakeします。
実行すると、画面は以下のようになります。


    上に戻る