我用谷歌搜索并找到了 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/