我可以在按下按钮时在Qt
中绘制默认的QWidget
,或者我总是创建QWidget
的子类并使用其paintEvent()
方法?
不讨论这种设计背后的意图,允许在没有子类的情况下对所有小部件进行共同绘制,我们可以这样做:
class MyEventFilter : public QObject
{
public:
MyEventFilter(QObject *parent = 0) : QObject(parent)
{}
bool eventFilter(QObject *obj, QEvent *e)
{
if (e->type() == QEvent::Paint)
{
QPaintEvent *ptrPaintEvent = static_cast<QPaintEvent *>(e);
// depending on whether or not you want to have a default handling for this:
// QObject::eventFilter(obj, e);
// OR better to apply to specific event handler, pass widget as parent for this filter object for that
// static_cast<QWidget*>(parent())->paintEvent(ptrPaintEvent);
// now do same thing as you would in paintEvent()
return true;
}
// standard event processing
return QObject::eventFilter(obj, e);
}
};
// and attach it to just any widget
myWidget->installEventFilter(new MyEventFilter(myWidget));