Qt 如何确定样式支持自定义控件元素

Qt 如何确定样式支持自定义控件元素,qt,Qt,我已经实现了一个自定义小部件,并引入了新的控制元素CE_MYShapedFrame。现在我的小部件不能使用标准样式,因为它们不知道CE_MYShapedFrame。我需要更改我的小部件以使用标准样式 void MyWidget::paintEvent(QPainter* painter) { if (this->style()->supports(CE_MYShapedFrame) { style->drawControl(CE_MYShapedFram

我已经实现了一个自定义小部件,并引入了新的控制元素CE_MYShapedFrame。现在我的小部件不能使用标准样式,因为它们不知道CE_MYShapedFrame。我需要更改我的小部件以使用标准样式

void MyWidget::paintEvent(QPainter* painter)
{
    if (this->style()->supports(CE_MYShapedFrame) {
        style->drawControl(CE_MYShapedFrame, &opt, painter);
    } else 
        style->drawControl(CE_ShapedFrame, &opt, painter);
    }
}
所以我的问题是:
有没有一种方法可以编写条件,比如if(this->style()->supports(CE\u MYShapedFrame)。

您知道标准Qt样式不支持此功能。但是您的自定义样式会支持此功能。因此,您可以简单地检查它是否是您的样式:

if (dynamic_cast<MyStyle>(style()) {
  style()->drawControl(CE_MYShapedFrame, &opt, painter);
} else {
  style()->drawControl(CE_ShapedFrame, &opt, painter);
}
if(动态_-cast(style()){
style()->drawControl(CE_MYShapedFrame和opt、painter);
}否则{
style()->drawControl(CE_ShapedFrame,&opt,painter);
}
如果您希望有多种样式可以支持它,那么可以引入一个公共接口,并在运行时检查它是否存在

#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QStyle>
#include <QStyleOption>
#include <QEventLoop>

class IClever {
public:
    virtual bool supports(QStyle::ControlElement) = 0;
    static IClever * cast(QStyle * style) {
        return dynamic_cast<IClever*>(style);
    }
};

class MyStyle : public QStyle, public IClever {
    bool supports(QStyle::ControlElement el) { }
    //...
};

enum { kCE_MYShapedFrame };
QStyle::ControlElement CE_MYShapedFrame() {
    return (QStyle::ControlElement)kCE_MYShapedFrame;
}

class MyWidget : public QWidget {
    void paintEvent(QPaintEvent*) {
        QStyleOption opt;
        opt.initFrom(this);
        QPainter painter(this);
        if (IClever::cast(style()) && IClever::cast(style())->supports(CE_MYShapedFrame())) {
            style()->drawControl(CE_MYShapedFrame(), &opt, &painter);
        } else {
            style()->drawControl(QStyle::CE_ShapedFrame, &opt, &painter);
        }
    }
};
#包括
#包括
#包括
#包括
#包括
#包括
阶级领袖{
公众:
虚拟布尔支持(QStyle::ControlElement)=0;
静态iCalver*转换(QStyle*样式){
返回动态_cast(样式);
}
};
类MyStyle:公共QStyle,公共IClever{
bool支持(QStyle::ControlElement el){}
//...
};
枚举{kCE_MYShapedFrame};
QStyle::ControlElement CE_MYShapedFrame(){
返回(QStyle::ControlElement)kCE_MYShapedFrame;
}
类MyWidget:publicqwidget{
无效paintEvent(QPaintEvent*){
qstyleopt;
选择从(本)开始;
油漆工(本);
if(IClever::cast(style())和&IClever::cast(style())->支持(CE_MYShapedFrame()){
style()->drawControl(CE_MYShapedFrame()、&opt和&painter);
}否则{
style()->drawControl(QStyle::CE_ShapedFrame、opt和painter);
}
}
};
您的
paintEvent()
签名错误。