QMessageBox类提供了一个可以与用户交互(如提示信息、提问题让用户进行某种选择)的模态对话框,注意,是模态对话框!它提供了两个构造函数实现对消息框的初始化。
通过构造函数创建QMessageBox
1、QMessageBox(QWidget *parent = Q_NULLPTR)
参数为父窗体指针。使用此函数构造消息对话框后要结合其他成员函数,如setIcon(),setWindowText(), setText(),setStandardButtons(),setDefaultButton()等实现对其标题、图标、消息文本、按钮等元素的初始化;需要注意的是setIcon()设定的icon是系统自带的,其参数是枚举类型Icon,如NoIcon,Question,Information等,如用户想自己设定图标,应使用setIcon
示例如下:(新建Qt widgets application,添加按钮,添加槽函数,在槽函数中实现)
QMessageBox msg(this);
msg.setIcon(QMessageBox::Warning);
msg.setWindowTitle("warning");
msg.setText("this is a test messagebox");
msg.setStandardButtons(QMessageBox::Yes|QMessageBox::No);
msg.setDefaultButton(QMessageBox::Yes);
msg.exec();
按下测试按钮,弹出消息框如下:
ps:QMessageBox类提供了丰富的成员函数实现用户的各种需求,比如可以使用setInformativeText()可以添加提示信息,以帮助用户理解消息框中的内容,setDetailedText()可以添加细节显示按钮,给用户提供更多辅助信息。
2、QMessageBox(Icon icon, const QString &title, const QString &text, StandardButtons buttons = NoButton, QWidget *parent = Q_NULLPTR, Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint)
主要关注前三个参数即可,分别是:显示图标(不是对话框标题栏的图标),标题,消息文本。第四个参数为按钮设置,默认为无按钮,可以通过使用StandButton的组合实现,如QMessageBox::Ok|QMessageBox::Cancel,第五个参数为父窗口指针。
示例如下:
QMessageBox msg(QMessageBox::NoIcon,"message",slices[0] + "**" +slices[1]);
msg.setIconPixmap(QPixmap(":/btnImg/image/default.png"));
msg.setIconPixmap(QPixmap("plus-normal.png"));
msg.exec();
其中:/btnImg/image/default.png是我添加的资源文件中的一个文件的url。
通过静态成员函数实现常用消息框
除通过构造函数来实现QMessageBox之外,我们还可以通过QMessageBox的静态成员函数实现几种常用的对话框:如关于对话框,错误提示对话框,信息提示对话框,警告对话框等
void about(QWidget *parent, const QString &title, const QString &text)
void aboutQt(QWidget *parent, const QString &title = QString())
StandardButton critical(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)
StandardButton information(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)
StandardButton question(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = StandardButtons( Yes | No ), StandardButton defaultButton = NoButton)
StandardButton warning(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton)
exec()函数
The exec() slot returns the StandardButtons value of the button that was clicked.
通过此函数的返回值判断用户选择了何种操作。注意,在创建QMessageBox之后,消息框并不能显示。为了使其显示出来,我们使用的是exec()函数,而不是show(),因为这是一个模态对话框,需要有它自己的事件循环,否则的话,对话框将会一闪而过。