2

我实现了一个自定义 QMessageBox,继承自 QDialog。(使用 qt 4.8.6)

现在的问题是所有自定义消息框看起来与 QMessageBox 静态函数完全不同:

  • QMessageBox::信息(...)
  • QMessageBox::critical(...)
  • QMessageBox::问题(...)
  • QMessageBox::警告(...)

它们在大小、字体、字体大小、图标、背景(静态 qmessagebox 有两种背景颜色)等方面有所不同...。

我发现的唯一一件事是如何访问操作系统特定的消息框图标。

QStyle *style = QApplication::style();
QIcon tmpIcon = style->standardIcon(QStyle::SP_MessageBoxInformation, 0, this);//for QMessageBox::Information

字体或整个样式是否有类似的东西。

我知道 QMessagebox 使用操作系统特定的样式指南。但我找不到他们。您可以在此处查看源代码。

所以我的问题是如何使从 QDialog 继承的自定义 QMessageBox 看起来像静态 QMessageBox::... 函数?

(如果我可以访问在此静态函数调用中创建的 QMessageBox 对象,我可以读出所有样式和字体参数。但这是不可能的。)

4

2 回答 2

0

实际上,您可以在不创建自己的自定义类的情况下完成大部分事情。 QMessageBox提供了一组应该对您有用的方法。这是一个例子:

QMessageBox msgBox;
msgBox.setText(text);
msgBox.setWindowTitle(title);
msgBox.setIcon(icon);

msgBox.setStandardButtons(standardButtons);
QList<QAbstractButton*> buttons = msgBox.buttons();
foreach(QAbstractButton* btn, buttons)
{
    QMessageBox::ButtonRole role = msgBox.buttonRole(btn);
    switch(role)
    {
        case QMessageBox::YesRole:
            btn->setShortcut(QKeySequence("y"));
        break;
        case QMessageBox::NoRole:
            btn->setShortcut(QKeySequence("n"));
        break;
    }
}
于 2014-09-29T11:13:27.363 回答
0

有点晚了,但今天我遇到了类似的问题,与添加新元素无关,而是与更改其中一些元素有关。我的解决方案:使用QProxyStyle(Qt 5+)。它基本上允许您仅重新实现基本样式的某些方面,而无需完全重新实现它。如果您使用由QStyleFactory.

这是一个覆盖默认图标的示例QMessageBox::information

class MyProxyStyle : public QProxyStyle {
public:
  MyProxyStyle(const QString& name) :
    QProxyStyle(name) {}

  virtual QIcon standardIcon(StandardPixmap standardIcon,
                             const QStyleOption *option,
                             const QWidget *widget) const override {
    if (standardIcon == SP_MessageBoxInformation)
      return QIcon(":/my_mb_info.ico");
    return QProxyStyle::standardIcon(standardIcon, option, widget);
  }
};

然后为您的应用设置样式:

qApp->setStyle(new MyProxyStyle("Fusion"));
于 2017-03-08T12:54:11.433 回答