Qt c++ 中的QMessageBox如何判断点击的按钮是QMessageBox::YesRole
时间: 2023-12-04 19:38:35 浏览: 192
在Qt c++中,QMessageBox的按钮有默认的标准按钮,也可以自定义按钮文字。如果想要判断点击的按钮是QMessageBox::YesRole,可以使用QMessageBox::buttonRole()函数获取被点击按钮的角色,然后与QMessageBox::YesRole进行比较即可。具体实现可以参考以下代码:
```
QMessageBox msgBox;
msgBox.setText("Do you want to save the changes?");
QAbstractButton* yesButton = msgBox.addButton(tr("Yes"), QMessageBox::YesRole);
QAbstractButton* noButton = msgBox.addButton(tr("No"), QMessageBox::NoRole);
QAbstractButton* cancelButton = msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
msgBox.exec();
if (msgBox.clickedButton() == yesButton && msgBox.buttonRole(yesButton) == QMessageBox::YesRole) {
// 点击了Yes按钮
} else if (msgBox.clickedButton() == noButton && msgBox.buttonRole(noButton) == QMessageBox::NoRole) {
// 点击了No按钮
} else if (msgBox.clickedButton() == cancelButton && msgBox.buttonRole(cancelButton) == QMessageBox::RejectRole) {
// 点击了Cancel按钮
}
```
阅读全文