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

有很多资料用于将 QMessageBox 的 OK 改为中文。但大多很麻烦。本文提供一个简便方法,用于定制 QMessageBox 的按钮,包括将其翻译成中文显示。
 
QMessageBox  对其内部的 Button 进行维护,用户可以使用 addButton() 方法,以及 removeButton() 方法添加或者移除按钮。每个 Button 都有个角色属性(enum QMessageBox::ButtonRole),用于标识该 Button 的用途。
角色属性列表如下:
Constant Value Description
QMessageBox::InvalidRole -1 The button is invalid.
QMessageBox::AcceptRole 0 Clicking the button causes the dialog to be accepted (e.g. OK).
QMessageBox::RejectRole 1 Clicking the button causes the dialog to be rejected (e.g. Cancel).
QMessageBox::DestructiveRole 2 Clicking the button causes a destructive change (e.g. for Discarding Changes) and closes the dialog.
QMessageBox::ActionRole 3 Clicking the button causes changes to the elements within the dialog.
QMessageBox::HelpRole 4 The button can be clicked to request help.
QMessageBox::YesRole 5 The button is a "Yes"-like button.
QMessageBox::NoRole 6 The button is a "No"-like button.
QMessageBox::ApplyRole 8 The button applies current changes.
QMessageBox::ResetRole 7 The 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的相关帮助文档。
 
http://blog.csdn.net/desert187/article/details/40302049
posted @   findumars  Views(6109)  Comments(0Edit  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示