【问题标题】:Where does QMessageBox get its styleguide, font-size, ... from?QMessageBox 从哪里获得它的样式指南、字体大小、...?
【发布时间】:2014-11-23 18:05:27
【问题描述】:

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

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

  • QMessageBox::信息(...)
  • QMessageBox::critical(...)
  • QMessageBox::question(...)
  • QMessageBox::warning(...)

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

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

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

字体或整个样式是否有相似之处。

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

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

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

【问题讨论】:

    标签: qt qmessagebox qstyle


    【解决方案1】:

    实际上,您可以在不创建自己的自定义类的情况下完成大多数事情。 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;
        }
    }
    

    【讨论】:

    • 我想添加一个复选框“不再显示此消息”
    • @user1911091 QErrorMessage 可以为你工作吗?
    • 不,我们在整个应用程序中使用 4 个消息框(警告、问题、关键、信息)。 QErrorMessage风格也喜欢操作系统吗?
    【解决方案2】:

    有点晚了,但今天我遇到了类似的问题,与添加新元素无关,而是与更改其中一些元素有关。我的解决方案:使用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"));
    

    【讨论】:

      猜你喜欢
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2016-05-02
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多