0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

はじめてC++で画面を作ろう! (5) getSaveFileName編

Last updated at Posted at 2021-05-31

15.「名前を付けて保存」を作ろう!!

手順は、前回の「ファイルを開く」編とさほど変わりがない。

[1] actionOpenに処理を書く
アクションエディタ画面より、「actionOpen」をクリック、続けてマウスの右ボタンをクリックすると、ポップアップ メニューが表示されるので、「スロットへ移動」をクリックします。

QAction trggered()をタプルクリックすると、自動的にC++のエディタに移動します。

mainwindow.cpp
# include "mainwindow.h"
# include "./ui_mainwindow.h"
# include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
   ...中略...

void MainWindow::on_actionSaveAs_triggered()
{
    
}

on_actionSaveAs_triggered()関数にカーソルが移動しています。

[2] QFileDialogをインクルードを確認
前回の「ファイルを開く」編で、既にQFileDialogをインクルード済なので、ここでは確認のみです。

[3] ファイル名の変数を用意
次にファイル名を入れる変数を用意します。
Qt5の文字列型の変数 (変数名:fileName)

mainwindow.cpp
# include "mainwindow.h"
# include "./ui_mainwindow.h"
# include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
   ...中略...

void MainWindow::on_actionSaveAs_triggered()
{
    QString fileName; /* これを追加 */
}

[4] 「名前を付けて保存」画面を呼び出す
次に用意した変数に「名前を付けて保存」画面の戻り値を入れます。

mainwindow.cpp
# include "mainwindow.h"
# include "./ui_mainwindow.h"
# include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
   ...中略...

void MainWindow::on_actionSaveAs_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), "", tr("Text File(*.txt)"));
}

[5] ステータスバーに表示する
前回と同様 せっかく、戻り値で、ファイル名を取得したので、とりあえずステータスバーに表示しましょう!!

mainwindow.cpp
# include "mainwindow.h"
# include "./ui_mainwindow.h"
# include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
   ...中略...

void MainWindow::on_actionSaveAs_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), "", tr("Text File(*.txt)"));
    ui->statusbar->showMessage(fileName); /* これを追加 */
}

16.動作確認!!

画面の左下にある、右三角マークの「実行」ボタンをクリックすると、何やら右下側にビルドしている状況が表示され、「MainWindow」が出てくる!

作ったアプリのメニューで、[File | SaveAs]で、「名前を付けて保存」画面が動く事をを確認しましょう!!

「名前を付けて保存」画面で、「キャンセル」ボタンをクリックすると、fileName = ""となる。

既にあるファイルをファイル名に指定した時は、自動的に__「○○は既に存在します。上書きしますか?」__と聞いてくる。

拡張子を省略しても、選択しているフィルターで、自動で拡張子が付く。

17.getSaveFileName関数の引数の説明

[1] this :ここは、親オブジェクトの設定
[2] tr("SaveAs") :ここは、「名前を付けて保存」のタイトル
[3] "" :ここは、画面を呼び出した時のファイルパス
「マイ ドキュメント」などを設定できる。
[4] tr("Text File( *.txt )") :ここは、拡張子のフィルター
フィルターは、セミコロン(;)を二つで区切りする

フィルターは、拡張子を自動的に付けるため、「ファイルを開く」の時のような、複数径は、使わないようにしましょう。

悪い例:Text File(*.txt *.xml *.json)
良い例:Text File(.txt);;XML File(.xml);;JSON File(*.json)

今回は、ここまで次回は、「ファイル情報をチェックする」を作ろう!!です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?