本文对 QMessageBox::Information, QMessageBox::Warning,QMessageBox::Critical 三种消息框进行演示。
并实现两种弹出方式:
1. 等待用户点击后关闭
2. 延时一段时间后自行关闭
效果如下:
以下是代码:
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMessageBox> //添加头文件
#include <QTime> //添加头文件
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
void MessBox(QMessageBox::Icon messboxIcon, QString str,int ms); //添加成员函数声明
void delayMSec(unsigned int msec); //添加成员函数声明
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
//QT简单入门实例3【QMessageBox使用,可实现自行关闭】
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
MessBox(QMessageBox::Information,"这是一个信息框,等待用户点击后关闭",0);
MessBox(QMessageBox::Information,"这是一个信息框,一段时间延时后关闭",1000);
MessBox(QMessageBox::Warning,"这是一个警告框,等待用户点击后关闭",0);
MessBox(QMessageBox::Warning,"这是一个警告框,一段时间延时后关闭",1000);
MessBox(QMessageBox::Critical,"这是一个严重错误框,等待用户点击后关闭",0);
MessBox(QMessageBox::Critical,"这是一个严重错误框,一段时间延时后关闭",1000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::delayMSec(unsigned int msec)
{
QTime Time_set = QTime::currentTime().addMSecs(msec);
while( QTime::currentTime() < Time_set )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}
void MainWindow::MessBox(QMessageBox::Icon messboxIcon, QString str, int ms)
{
if(ms==0){
if(messboxIcon==QMessageBox::Information)
QMessageBox::information(this, tr("消息"),str, QMessageBox::Ok | QMessageBox::Cancel);
else if(messboxIcon==QMessageBox::Warning)
QMessageBox::warning(this, tr("警告"), str, QMessageBox::Ok );
else if(messboxIcon==QMessageBox::Critical)
QMessageBox::critical(this, tr("错误"), str, QMessageBox::Ok );
else
QMessageBox::question(this, tr("未知"),str, QMessageBox::Ok );
}
else if(ms>0){
QMessageBox* box;
box = new QMessageBox("Messagebox", str, messboxIcon, \
QMessageBox::Ok | QMessageBox::Default, QMessageBox::Cancel | QMessageBox::Escape, 0);
box->show();
delayMSec(ms);
box->hide();
delete box;
}
}
关于如何获取ok和cancel点击信号,以执行不同的后续操作,请看本系列下一篇文章:
QT简单入门实例4【QMessageBox确定和取消功能】