C++ 获取qt中标签的鼠标单击位置

C++ 获取qt中标签的鼠标单击位置,c++,qt,user-interface,location,mouseevent,C++,Qt,User Interface,Location,Mouseevent,我在谷歌上搜索了一下,发现其中的OP似乎和我的问题完全一样。问题是,我如何从QLabel继承并重新实现mousepressed事件?我猜是这样的: class CustomLabel : public QLabel { public: //what about the constructors? void mousePressEvent ( QMouseEvent * ev ); } void CustomLabel::mousePressEvent ( QMouseEvent

我在谷歌上搜索了一下,发现其中的OP似乎和我的问题完全一样。问题是,我如何从
QLabel
继承并重新实现mousepressed事件?我猜是这样的:

class CustomLabel : public QLabel
{
public:
    //what about the constructors?
    void mousePressEvent ( QMouseEvent * ev );
}

void CustomLabel::mousePressEvent ( QMouseEvent * ev )
{
    QPoint = ev->pos();
    //I want to have another function get the event position.
    //How would I achieve this? It's void!
    //Is there perhaps some way to set up a signal and slot with the position?
}

在我成功创建了一个
CustomLabel
类之后,我如何才能将它放在设计视图中?

是我自己,还是
QMouseEvent
已经提供了您需要的信息

int QMouseEvent::x()常量

返回鼠标光标相对于接收事件的小部件的x位置

另请参见y()和pos()

int QMouseEvent::y()常量

返回鼠标光标相对于接收事件的小部件的y位置

另请参见x()和pos()


Ref:

是的,您可以在
CustomLabel
类上设置一个信号,并让覆盖版本的
mousePressEvent
发出该信号。i、 e

class CustomLabel : public QLabel
{
Q_OBJECT
signals:
    void mousePressed( const QPoint& );

public:
    CustomLabel( QWidget* parent = 0, Qt::WindowFlags f = 0 );
    CustomLabel( const QString& text, QWidget* parent = 0, Qt::WindowFlags f = 0 );

    void mousePressEvent( QMouseEvent* ev );
};

void CustomLabel::mousePressEvent( QMouseEvent* ev )
{
    const QPoint p = ev->pos();
    emit mousePressed( p );
}

CustomLabel::CustomLabel( QWidget * parent, Qt::WindowFlags f )
    : QLabel( parent, f ) {}

CustomLabel::CustomLabel( const QString& text, QWidget* parent, Qt::WindowFlags f )
    : QLabel( text, parent, f ) {}
构造函数只是模仿基本的
QLabel
,因此只需将其参数直接传递给相应的基本构造函数。

如下所示:D

void CustomLabel::mousePressEvent(QMouseEvent *ev) 
{
QString x = QString::number(ev->x());
QString y = QString::number(ev->y());
qDebug() << x << "," << y;
}
void CustomLabel::mousePressEvent(QMouseEvent*ev)
{
QString x=QString::number(ev->x());
QString y=QString::number(ev->y());

qDebug()哦,好的,对不起!我怎么知道是否有鼠标点击,然后得到位置?我怎么才能将这样一个自定义标签添加到design view?@ErrorUserName:恐怕我不知道该怎么做。对不起。没关系,别担心,我最后使用了一个事件过滤器,而不是你找到了将标签放回主窗口的第二种解决方案了吗?