c++ - 在qt中获取标签的鼠标点击位置

标签 c++ qt user-interface location mouseevent

我用谷歌搜索并找到了 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 类之后,我如何才能将它放入设计 View 中?

最佳答案

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

关于c++ - 在qt中获取标签的鼠标点击位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4349769/

相关文章:

c++ - 仅当存在数据竞争与锁定时才使用 OpenMP 临界区?

c++ - 以二进制方式使用 boost::asio::streambuf 进行顺序通信失败?

Xcode 相当于 Visual Studio 的 "Find Source"

java - GUI 停止工作,即使它在自己的线程中并且未调用 Thread.sleep()

javascript - 带参数的 Dat.gui 函数调用?

c++ - 使用宏打开/关闭 openmp

c++ - 哪个布局引擎用于查找网页上 html 元素的坐标?

c++ - 'QObject::QObject(const QObject&)' 是私有(private)的

c++ - Tor 控件去哪儿了?

.net - 支持视觉风格的控制按钮背景颜色