我希望能夠通過按下一個按鈕或一個鍵來啓用和禁用在我的整個QMainWindow上過濾鼠標點擊,這將導致過濾開始。我想從QMainWindow的類中啓用事件過濾器,以便我可以訪問它的方法。我遇到的問題是您似乎只能在對象上啓用事件過濾器,而不是從內部啓用事件過濾器。Qt - 在對象中安裝eventfilter
我希望能有我的類中的eventfilter我們可以稱之爲MyWindow
,從我發現我應該做一個新的類MouseFilter
,重新定義eventFilter(QObject* object,QEvent* event)
和mywindow的安裝
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
MyWindow w;
w.installEventFilter(new MouseFilter());
w.show();
return a.exec();
}
有沒有辦法從我的對象內部實現事件過濾器?我希望能夠做這樣的事情:
class MouseFilter : public QObject
{
Q_OBJECT
public:
explicit MouseFilter(QObject *parent = 0);
bool eventFilter(QObject* object,QEvent* event)
{
if (event->type() == (QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
if(mouseEvent->button() == Qt::RightButton){
// Disable certain buttons in MainWindow
otherMethod();
} else if (mouseEvent->button() == Qt::LeftButton){
// Something else
anotherMethod();
} else {
// ...
}
return true;
} else
{
return QObject::eventFilter(object, event);
}
};
private:
void anotherMethod();
void otherMethod();
public slots:
};
編輯: 好吧,我想我可能已經過於複雜的事情。是否像繼承mousePressEvent
那樣簡單?
例如:
void MouseFilter::mousePressEvent(QMouseEvent * event){
if(event->button() == Qt::RightButton){
qDebug() << "Right-o";
}
}
謝謝,我發現幾分鐘前,我想我正在推翻東西...... – johnramsden
@STREBLO大:)我認爲你應該將你的話題標記爲回答,這樣其他人不會浪費時間看它; ) – Rostislav