关闭

Qt Label添加点击事件

标签: Qtlabel点击clicked
3598人阅读 评论(0) 收藏 举报
分类:

Qt添加点击事件

A "clicked" signal may sometimes be required from a label, but there is no "clicked" signal emitted by QLabel. You can work around this easily by making a QPushButton like a label by setting the 'flat' property.

   在label上有可能需要一个“clicked”信号,但是在QLabel类中没有“clicked”信号,QPushButton更容易使用。

However, if there are other properties of a QLabel object that you need, here is a code snippet for a custom QLabel which can emit a signal: 'clicked'. In other words, a Clickable QLabel!

    然而,如果需要QLabel一些其他的属性,这里有自定义的QLabel发送'clicked'信号,就是,这个可点击的QLabel

Header

class ClickableLabel : public QLabel
{
Q_OBJECT
public:
    explicit ClickableLabel( const QString& text="", QWidget* parent=0 );
    ~ClickableLabel();
signals:
    void clicked();
protected:
    void mousePressEvent(QMouseEvent* event);};

Source

 

ClickableLabel::ClickableLabel(const QString& text, QWidget* parent)
    : QLabel(parent)
{
    setText(text);
}
 
ClickableLabel::~ClickableLabel()
{
 
}
void ClickableLabel::mousePressEvent(QMouseEvent* event)
{
    emit clicked();
}

What we do here is simple: Catch the mouse press event on the label. Then emit 'clicked' signal. We could as well make the signal be emitted when mouse gets released. This is let to be a decision of the developer.

这里是最简单的例子,在label上获取鼠标点击事件,然后发送'clicked'信号,可以当鼠标释放的时候发送信号,这由开发这定义。

http://wiki.qt.io/Make-a-QLabel-Clickable


下面是修改的mousePressEvent

void ClickLabel::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        emit clicked();
    }
 
    QLabel::mousePressEvent(event);//将该事件传给父类处理
}


2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30813次
    • 积分:715
    • 等级:
    • 排名:千里之外
    • 原创:42篇
    • 转载:3篇
    • 译文:0篇
    • 评论:6条
    最新评论