QMessageBox有critical、warning、question、about
四种类型,除了about
没有按钮设置之外,其余QMessageBox都有按钮设置,如 :
QMessageBox::warning(NULL, "warning", "Content", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
QMessageBox::about(NULL, "About", "About this application");
另外,除了about之外,其他QMessageBox都有自己的Icon;
1、常规用法:
以critical
为例,看构造函数便知用法多种多样:
static int critical(QWidget *parent, const QString &title,
const QString& text,
int button0, int button1, int button2 = 0);
static int critical(QWidget *parent, const QString &title,
const QString& text,
const QString& button0Text,
const QString& button1Text = QString(),
const QString& button2Text = QString(),
int defaultButtonNumber = 0,
int escapeButtonNumber = -1);
inline static int critical(QWidget *parent, const QString &title,
const QString& text,
StandardButton button0, StandardButton button1)
{ return critical(parent, title, text, StandardButtons(button0), button1); }
示例:
QMessageBox::StandardButton rb = QMessageBox::question(this, "Title", "Details", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if(rb == QMessageBox::Yes)
{
QMessageBox::aboutQt(NULL, "About Qt");
}
2、自定义用法:
2.1
QMessageBox question;
question.addButton("分钟值",QMessageBox::YesRole);//索引为0
question.addButton("小时值",QMessageBox::NoRole)->setDefault(true);//索引为1,设为默认按钮
int rd = question.exec();//返回值为所按按钮的索引
if(rd == 0)
qDebug()<<"666";
else if(rd == 1)
qDebug()<<"555";
注意:如果该QMEssageBox是局部变量,使用exec()函数,而不使用show(),才能让对话框成为模态对话框
,进入它自己的事件循环,否则,程序运行到该局部变量作用域外,对话框会被销毁,给人的感觉就是对话框一闪而过 。
QMessageBox *m_box = new QMessageBox(this);
m_box->setText("这是指针消息弹框!");
m_box->show();
- 在用户点击或指针被销毁之前,该弹框都会出现在界面上
//头文件:
QMessageBox *m_box;
//源文件:
m_box = new QMessageBox(this);
m_box->setText("这是指针消息弹框!");
m_box->show();
- 和上面的指针弹框一样,在用户点击或指针被销毁之前,该弹框都会出现在界面上
2.2
int id = QMessageBox::information(NULL, QString("提示"), QString("保存数据"),
QString("确定"),QString("取消"), QString("返回") );
//或
int id = QMessageBox::information(NULL, "提示","保存数据?",
QString("确定"), QString("取消"),QString("返回"),1);
//最后一个数字确定默认按钮,此处默认为第二个按钮,即 QString("取消"),当数字有多个时,
//第一个确定默认按钮,第二个表示信息框右上角关闭按钮可用,数字个数必须小于按钮数
switch (id) {
case 0:
{
//确定
//dosomething
}
break;
case 1:
{
//取消
//dosomething
}
break;
case 2:
{
//返回
//dosomething
}
break;
default:
break;
}