qlabelにクリックイベントclicked()を追加しevent

2094 ワード

2 ways:1) try deriving from QLabel and overwrite the event function:

Source code

1
2
3
4
5
6
7
8
9
10
11
12
bool event( QEvent * e )
    {
        bool retVal = QLabel::event(e);
        if (e->type() == QEvent:: MouseButtonPress)
        {
            foo();
           retVal = true;
        }

        return retVal;

    }

2) Try Adding eventFilter
 
Example:
 class MainWindow : public QMainWindow
 {
 public:
     MainWindow();

 protected:
     bool eventFilter(QObject *obj, QEvent *ev);

 private:
     QTextEdit *textEdit;
 };

 MainWindow::MainWindow()
 {
     textEdit = new QTextEdit;
     setCentralWidget(textEdit);

     textEdit->installEventFilter(this);
 }

 bool MainWindow::eventFilter(QObject *obj, QEvent *event)
 {
     if (obj == textEdit) {
         if (event->type() == QEvent::KeyPress) { // 
             QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
             qDebug() << "Ate key press" << keyEvent->key();
             return true;
         } else {
             return false;
         }
     } else {
         // pass the event on to the parent class
         return QMainWindow::eventFilter(obj, event);
     }
 }