本文介绍了在qt中获取标签的鼠标单击位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了一下,发现 QLabel 继承并重新实现mousepressed事件?我猜这将是这样的:

  class CustomLabel:public QLabel 
{
public :
//构造函数怎么样?
void mousePressEvent(QMouseEvent * ev);
}

void CustomLabel :: mousePressEvent(QMouseEvent * ev)
{
QPoint = ev-> pos
//我想有另一个函数获取事件位置。
//我该如何实现呢?这是无效的!
//有可能有一些方法来设置一个信号和槽位的位置?
}



在我成功创建了 CustomLabel 类,我如何能够把它放在设计视图中?

您的 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 的构造函数,因此简单地将它们的参数直接传递给相应的基础构造函数。 / p>

I googled around and found this forum thread in which the OP seems to have had the exact problem I am having. The question is, how would I inherit from QLabel and reimplement the mousepressed event? I'm guessing it would be something like this:

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?
}

And after I have successfully created a CustomLabel class, how would I be able to put it in design view?

解决方案

Yes, you can set up a signal on your CustomLabel class and have your overridden version of mousePressEvent emit it. 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 ) {}

The constructors just mimic those of the base QLabel and therefore simply pass their arguments straight on to the corresponding base constructors.

这篇关于在qt中获取标签的鼠标单击位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:58