c++ - 如何检测鼠标点击 QLineEdit

标签 c++ qt mouseevent qlineedit

在我的 QWidget 中有一些 subwidgets,例如 QLineEditQLabels。我可以很容易地检查我的鼠标是否在 QLabel 上以及是否单击了右键。 QLineEdit 不是这样。 我尝试子类化 QLineEdit 并重新实现 mouseRelease,但它从未被调用过。 findChild 方法是从我的 UI 中获取相应的小部件。

如何获取 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);

标签上的点击被识别,但 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...
        }
    }

最佳答案

我似乎能够检测到对行编辑的点击,并区分它在下面发布的类中是哪种类型,这与在提到的链接中发布的非常相似

#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

#include "QApplication"

#include "myclass.h"

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

  MyClass dialog;
  dialog.show();

  return app.exec();

}

关于c++ - 如何检测鼠标点击 QLineEdit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22128145/

相关文章:

c++ - 如何以多态方式使用替代类型的 std::variant

C++98/03 std::is_constructible 实现

c++ - 使用QTest模拟鼠标移动

javascript - IE 11 从空白区域选择文本时,光标不会立即更改

Java - 单击鼠标时,tick() 循环会导致多个操作

c++ - 在 Linux 上使用带有 g++ 的 RWTValHashMap 的奇怪问题

c++ - 如何使用 Clang AST 找到 VarDecl 类型定义的 SourceLocation?

c++ - MinGW 上支持 OpenMP 的 Qt 插件 : Undefined reference?

c++ - 我应该尽可能使用#ifndef Q_MOC_RUN 吗?

c# - 如何确定哪个鼠标按钮引发了 WPF 中的单击事件?