我有两个班级:
typedef std::shared_ptr<AdaptedWidget> window_ptr;
class WindowManager
{
public:
...
private:
std::stack<window_ptr> m_windowsStack;
}
和
class AdaptedWidget: public QWidget
{
Q_OBJECT
public:
AdaptedWidget(AdaptedWidget *parent = 0);
bool event(QEvent *event);
};
bool AdaptedWidget::event(QEvent *event)
{
if (event->type() == QEvent::NonClientAreaMouseButtonPress ||
event->type() == QEvent::MouseButtonPress)
{
qDebug() << "mainwindwo press";
}
return QWidget::event(event);
}
我需要从AdaptedWidget
对象获取WindowManager
个对象中发生的事件的信息,我该怎么做?
答案 0 :(得分:1)
Event filters是完成任务的Qt方法。
将WindowManager
类设为QObject
的子类,并为其eventFilter()
方法提供实现。
之后,每次创建AdaptedWidget
使用installEventFilter()
来安装WindowManager
实例作为事件过滤器。
class WindowManager : public QObject
{
public:
...
bool eventFilter(QObject* obj, QEvent* ev);
private:
std::stack<window_ptr> m_windowsStack;
}
和
bool WindowManager::eventFilter(QObject* obj, QEvent* ev){
AdaptedWidget* widget= qobject_cast<AdaptedWidget*>(obj);
if(ev->type == /*type of event you are interested in*/){
//you can compare widget against the stack of widgets you have
//if you want to stop widget from receiving the event you can return true
}
return false;
}
并在创建每个AdaptedWidget
实例时,将WindowManager
安装为事件过滤器:
AdaptedWidget* widget= new AdaptedWidget;
widget->installEventFilter(/*your WindowManager instance*/);
答案 1 :(得分:1)
AdaptedWidget
类应该有一个表示鼠标按下的信号,例如
class AdaptedWidget : ... {
Q_OBJECT
...
public:
Q_SIGNAL void mousePress(const QPoint &);
};
bool AdaptedWidget::event(QEvent *event)
{
if (event->type() == QEvent::NonClientAreaMouseButtonPress ||
event->type() == QEvent::MouseButtonPress)
{
auto ev = static_cast<QMouseEvent*>(event);
emit mousePress(ev->pos());
qDebug() << "mainwindow press";
}
return QWidget::event(event);
}
另一种方法是使用事件过滤器,但不必要地紧密耦合这两个类。