main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QDialog>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
QDialog dlg;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include<QMenuBar>
#include<QMenu>
#include<QAction>
#include<QDebug>
#include<QDialog>//对话框
#include<QMessageBox>//静态对话框
#include<QFileDialog>//文件对话框
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QMenuBar *mBar=menuBar();
setMenuBar(mBar);
QMenu *menu=mBar->addMenu("对话框!");
QAction *p1=menu->addAction("模态对话框");//操作模态对话框时不可操作其他的
connect(p1,&QAction::triggered,
[=]()
{
QDialog dlg;
dlg.exec();
qDebug()<<"111111";
}
);
QAction *p2=menu->addAction("非模态对话框");//操作非模态对话框时可以操作其他的
connect(p2,&QAction::triggered,
[=]()
{
// QDialog dlg;
// dlg.show();
// qDebug()<<"222222";//这里结束后不会显示出来,所以解决方法1就是将dlg声明成成员对象
// //方法2:动态分配内存空间
// QDialog *p=new QDialog(this);
// p->show();
// QDebug()<<"2222222222";
// //这种方法存在弊端,就是不释放p的空间,所以不指定父对象就可以了
QDialog *p=new QDialog();
p->setAttribute(Qt::WA_DeleteOnClose);
p->show();
}
);
QAction *p3=menu->addAction("关于对话框");
connect(p3,&QAction::triggered,
[=]()
{
QMessageBox::about(this,"about","关于qt");//第一个参数:指定父对象,第二个参数:标题,第三个参数:内容
}
);
QAction *p4=menu->addAction("问题对话框");
// connect(p4,&QAction::triggered,
// [=]()
// {
// int ret=QMessageBox::question(this,"question","Are you ok?");//第一个参数:指定父对象,第二个参数:标题,第三个参数:内容。
// //不用管按钮,系统默认给两个按钮,返回值是枚举类型
// switch(ret)
// {
// case QMessageBox::YES:
// qDebug()<<"i am ok!";
// break;
// case QMessageBox::NO:
// qDebug()<<"i am bad!";
// break;
// default:
// break;
// }
// }
// );
//可以指定按钮
connect(p4,&QAction::triggered,
[=]()
{
int ret=QMessageBox::question(this,"question","Are you ok?",QMessageBox::OK|QMessageBox::Cancel);
switch(ret)
{
case QMessageBox::OK:
qDebug()<<"i am ok!";
break;
case QMessageBox::Cancel:
qDebug()<<"i am bad!";
break;
default:
break;
}
}
);
QAction *p5=menu->addAction("文件对话框");
connect(p5,&QAction::triggered,
[=]()
{
QString path=QFileDialog::getOpenFileName(this,
"open",
"../",
"sorce(*.cpp *.h);;"
" Text(*.txt);;all(*.*)");//第一个参数:指定父对象,第二个参数:名字,第三个参数:文件路径(..表示上一个路径),有返回值,字符串。
qDebug()<<path;
}
);
}
MainWindow::~MainWindow()
{
}