myapp.h
#ifndef MYAPP_H
#define MYAPP_H
#include <QtWidgets/QMainWindow>
#include "ui_myapp.h"
class QLabel;
class QAction;
class MyApp : public QMainWindow
{
Q_OBJECT
public:
MyApp(QWidget *parent = 0);
~MyApp();
private:
Ui::MyAppClass ui;
QAction *openAction;
QLabel *msgLabel;
void open();
};
#endif // MYAPP_H
myapp.cpp
#include "myapp.h"
#include <qpushbutton.h>
#include <qmenu.h>
#include <qmenubar.h>
#include <qkeysequence.h>
#include <qtoolbar.h>
#include <qlabel.h>
#include <qstatusbar.h>
#include <qaction.h>
#include <qstring.h>
#include <qfiledialog.h>
#include <qmessagebox.h>
MyApp::MyApp(QWidget *parent)
: QMainWindow(parent)
{
//setMinimumSize(200,120);
//setMaximumSize(200,120);
//QPushButton *quit = new QPushButton("Quit");
//quit->setGeometry(100,100,80,100);
//QObject::connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
//quit->show();
openAction = new QAction(tr("&open"), this);
openAction->setShortcut(QKeySequence::Open);
openAction->setStatusTip(tr("Open a file."));
connect(openAction,&QAction::triggered,this,&MyApp::open);
QMenu *file = menuBar()->addMenu(tr("&File"));
file->addAction(openAction);
QToolBar *toolBar = addToolBar(tr("&File"));
toolBar->addAction(openAction);
msgLabel = new QLabel;
msgLabel->setMinimumSize(msgLabel->sizeHint());
msgLabel->setAlignment(Qt::AlignHCenter);
statusBar()->addWidget(msgLabel);
//删除状态栏的短竖线(当没有状态文字时出现的短竖线)
statusBar()->setStyleSheet(QString("QStatusBar::item{border: 0px}"));
//ui.setupUi(this);
}
MyApp::~MyApp()
{
}
void MyApp::open()
{
QString path = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image Files(*.jpg *.png)"));
if(path.length()==0)
{
QMessageBox::information(NULL, tr("Path"), tr("You didn't select any file."));
}
else
{
QMessageBox::information(NULL, tr("Path"), tr("You selected ") + path);
}
}
main.cpp
#include "myapp.h"
#include <qapplication.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyApp my;
my.show();
return app.exec();
}
运行:
说明:
1、主要是添加一个QAction *openAction,这个用来关联打开对话框的操作,菜单和工具栏都是同一个QAction:
connect(openAction,&QAction::triggered,this,&MyApp::open);
然后使用QFileDialog中的getOpenFileName()这个函数获取选中的文件名:
QString path = QFileDialog::getOpenFileName(this, tr("Open Image"), ".", tr("Image Files(*.jpg *.png)"));
这个函数定义了对话框的标题,过滤,返回的是选中的文件目录。