在我的 QWidget
中有一些 subwidgets
,例如 QLineEdit
和 QLabels
。我可以很容易地检查我的鼠标是否在 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/