扩展QMessageBox类时如何访问QMessageBoxPrivate中的label变量?

时间:2013-11-25 04:10:23

标签: c++ qt

我需要扩展QMessageBox以将标签的QTextInteractionFlags设置为Qt :: TextSelectableByMouse | Qt :: TextSelectableByKeyboard。

我检查了qmessagebox.cpp的

void QMessageBox::setText(const QString &text)
{
    Q_D(QMessageBox);
    d->label->setText(text);
    d->label->setWordWrap(d->label->textFormat() == Qt::RichText
        || (d->label->textFormat() == Qt::AutoText && Qt::mightBeRichText(text)));
    d->updateSize();
}

我需要这样的代码:

void QMessageBox::setTextInteractionFlags ( Qt::TextInteractionFlags flags )
{
    Q_D(QMessageBox);
    d->label->textInteractionFlags(flags);
}

那么如何扩展QMessageBox并在QMessageBox上获取d指针?好像我需要访问QMessageBoxPrivate类。

1 个答案:

答案 0 :(得分:1)

Subcalss QStyle之一并重新实现styleHint方法。

#include <QCommonStyle>

class MyStyle : public QCommonStyle
{
public:
    explicit MyStyle() {}
    int styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *widget, QStyleHintReturn *hret) const
    {
        if (SH_MessageBox_TextInteractionFlags == sh)
        {
           return Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard;
        }
        return QCommonStyle::styleHint(sh, opt, widget, hret);
    }
};

将您的样式应用于消息框。

QMessageBox msgBox;
msgBox.setText("This is something text.");
msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
msgBox.setStyle(new MyStyle);
int ret = msgBox.exec();