Qt/C++中调整QMessageBox窗口图标、标题并居中按钮的实现方法
QMessageBox自定义方案
问题原因说明
- 窗口图标不生效:你调用
setWindowIcon(QIcon())时传入了空的QIcon实例,没有加载有效图标资源,自然无法显示。 - 窗口标题不生效:你误调用了
setWindowIconText()设置窗口标题,这个接口是设置窗口图标的悬浮提示文本,设置窗口标题应该用setWindowTitle()。你现在看到的PanoramaCreator是QMessageBox默认继承了父窗口的标题。 - 按钮居中实现:QMessageBox的按钮默认放在
QDialogButtonBox容器中,该容器自带setCenterButtons()接口可以直接设置按钮居中,不需要额外调整布局。
完整修改后代码
#include <QDialogButtonBox> #include <QStyle> // just for the color understanding const QColor BG_COLOR = QColor(125,125,125); QString setColorBG = "{background: rgb(" + QString::number(BG_COLOR.red()) + "," + QString::number(BG_COLOR.green()) + "," + QString::number(BG_COLOR.blue()) + ");}"; QMessageBox msg; msg.setText("Please select images."); msg.setIcon(QMessageBox::Warning); // 设置窗口标题 msg.setWindowTitle("Warning"); // 传入有效图标,这里用Qt自带的警告图标做示例,也可以替换为你自己的资源路径 msg.setWindowIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxWarning)); // 设置OK按钮居中 QDialogButtonBox* btnBox = msg.findChild<QDialogButtonBox*>(); if (btnBox) { btnBox->setCenterButtons(true); } msg.setStyleSheet("QMessageBox QPushButton{background: rgb(173,173,173);}" "QMessageBox " + setColorBG); msg.exec();
注:如果是Linux桌面环境下窗口图标仍不显示,属于系统桌面策略限制,不属于代码问题。
内容的提问来源于stack exchange,提问作者Miau
相关产品推荐
相关产品推荐

