QMessageBox 中的 OK 按钮改为中文“确定”

来源:互联网 发布:淘宝上阿玛尼都是假的 编辑:程序博客网 时间:2024/05/16 09:01
有很多资料用于将 QMessageBox 的 OK 改为中文。但大多很麻烦。本文提供一个简便方法,用于定制 QMessageBox 的按钮,包括将其翻译成中文显示。

QMessageBox  对其内部的 Button 进行维护,用户可以使用 addButton() 方法,以及 removeButton() 方法添加或者移除按钮。每个 Button 都有个角色属性(enum QMessageBox::ButtonRole),用于标识该 Button 的用途。
角色属性列表如下:
ConstantValueDescriptionQMessageBox::InvalidRole-1The button is invalid.QMessageBox::AcceptRole0Clicking the button causes the dialog to be accepted (e.g. OK).QMessageBox::RejectRole1Clicking the button causes the dialog to be rejected (e.g. Cancel).QMessageBox::DestructiveRole2Clicking the button causes a destructive change (e.g. for Discarding Changes) and closes the dialog.QMessageBox::ActionRole3Clicking the button causes changes to the elements within the dialog.QMessageBox::HelpRole4The button can be clicked to request help.QMessageBox::YesRole5The button is a "Yes"-like button.QMessageBox::NoRole6The button is a "No"-like button.QMessageBox::ApplyRole8The button applies current changes.QMessageBox::ResetRole7The button resets the dialog's fields to default values.因此,用户可以使用 addButton() 和 removeButton() 方法,结合角色属性,来自定义 QMessageBox 的Button。
另外,用户可以通过 button() 或者 buttons() 方法获得“按键”或者“按键列表”。
QMessageBox 还提供了一个复杂的构造函数,用于在创建消息对话框时就对其进行定制,改构造函数原型如下:

QMessageBox::QMessageBox(Icon icon, const QString & title, const QString & text, StandardButtons buttons = NoButton, QWidget * parent = 0, Qt::WindowFlags f = Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint)

因此,我们得到了一个将 “OK” 按键变成“确定”按键的最简单思路:使用 button() 方法获得 QAbstractButton 按键,然后使用 QAbstractButton 的 setText() 方法将其重新命名为“确定”,示例代码如下:
    WrrMsg = new QMessageBox(QMessageBox::NoIcon, title, msg, QMessageBox::Ok, 0);
    if(NULL!=WrrMsg->button(QMessageBox::Ok))
    {
        WrrMsg->button(QMessageBox::Ok)->setText("确 定");
    }
其中,title为QString类型的窗口标题,msg为QString类型的消息内容,QMessageBox()具体信息请参见Qt的相关帮助文档。
0 0
原创粉丝点击