简体   繁体   English

如何检测鼠标单击QLineEdit

[英]How to detect mouse click on QLineEdit

In my QWidget there are some subwidgets like a QLineEdit and QLabels . 在我QWidget有一些subwidgets像一个QLineEditQLabels I can easily check if my mouse is over a QLabel and if it was clicked on the right button. 我可以轻松地检查鼠标是否在QLabel上,以及是否单击了右键。 Not so on QLineEdit . QLineEdit上不是这样。 I tried to subclass QLineEdit and re-implement the mouseRelease , but it is never called. 我尝试将QLineEdit子类化并重新实现mouseRelease ,但是从未调用过它。 The findChild method is to get the corresponding widget out off my UI. findChild方法是从我的UI中获取相应的小部件。

How do I get the mouseRelease and whether it's left or right mouse button in a QLineEdit ? 我如何获取mouseRelease以及QLineEdit鼠标左键或鼠标右键?

void Q_new_LineEdit::mouseReleaseEvent(QMouseEvent *e){
    qDebug() << "found release";
    QLineEdit::mouseReleaseEvent(e);
}

m_titleEdit = new Q_new_LineEdit();
m_titleEdit = findChild<QLineEdit *>("titleEdit",Qt::FindChildrenRecursively);

Clicks on labels are recognized, but the click on QLineEdit is not, like below: 可以识别标签上的单击,但不能识别QLineEdit上的单击,如下所示:

void GripMenu::mouseReleaseEvent(QMouseEvent *event){

    if (event->button()==Qt::RightButton){ 

        //get click on QLineEdit 
        if (uiGrip->titleEdit->underMouse()){
            //DO STH... But is never called
        }

        //change color of Label ...
        if (uiGrip->col1note->underMouse()){
            //DO STH...
        }
    }

I seem to be able to detect clicks on the line edit and distinguish which type it is in the class posted below which is very similar to what has been posted in the mentioned link 我似乎能够检测到行编辑上的点击,并在下面发布的类中区分它是哪种类型,这与提到的链接中发布的类型非常相似

#ifndef MYDIALOG_H
#define MYDIALOG_H

#include <QDialog>
#include <QMouseEvent>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QtCore>


class MyClass: public QDialog
{
  Q_OBJECT
    public:
  MyClass() :
  layout(new QHBoxLayout),
    lineEdit(new QLineEdit)

      {
        layout->addWidget(lineEdit);
        this->setLayout(layout);
        lineEdit->installEventFilter(this);
      }

  bool eventFilter(QObject* object, QEvent* event)
    {
      if(object == lineEdit && event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *k = static_cast<QMouseEvent *> (event);
        if( k->button() == Qt::LeftButton ) {
          qDebug() << "Left click";
        } else if ( k->button() == Qt::RightButton ) {
          qDebug() << "Right click";
        }
      }
      return false;
    }
 private:
  QHBoxLayout *layout;
  QLineEdit *lineEdit;

};


#endif

main.cpp for completeness main.cpp的完整性

#include "QApplication"

#include "myclass.h"

int main(int argc, char** argv)
{
  QApplication app(argc, argv);

  MyClass dialog;
  dialog.show();

  return app.exec();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM