【问题标题】:Getting mouse click location of a label in qt在qt中获取标签的鼠标单击位置
【发布时间】:2012-05-25 07:55:47
【问题描述】:

我四处搜索,发现this forum thread,其中 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 类之后,我如何才能将它放在设计视图中?

【问题讨论】:

  • 你找到第二个将标签放回主窗口的解决方案了吗?

标签: c++ qt user-interface location mouseevent


【解决方案1】:

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

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 的构造函数,因此只需将它们的参数直接传递给相应的基础构造函数。

【讨论】:

  • 如何将这样的自定义标签添加到设计视图中?
  • @wrongusername:恐怕我不知道该怎么做。对不起。
  • 没关系,别担心,我最终改用了事件过滤器
【解决方案2】:

就像这样:D

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

【讨论】:

    【解决方案3】:

    只有我一个人,还是QMouseEvent 没有提供您需要的信息?

    int QMouseEvent::x () 常量

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

    另见 y() 和 pos()。

    int QMouseEvent::y () 常量

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

    另见 x() 和 pos()。

    参考:http://doc.qt.nokia.com/4.7.old/qmouseevent.html#x

    【讨论】:

    • 哦,好吧,对不起!我怎么知道是否有鼠标点击然后获取位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多