Skip to content

Instantly share code, notes, and snippets.

@ixxra
Forked from jjfajardo/LinkLabel.cpp
Last active August 29, 2015 14:02
Show Gist options
  • Save ixxra/6282168bfc14898907bd to your computer and use it in GitHub Desktop.
Save ixxra/6282168bfc14898907bd to your computer and use it in GitHub Desktop.
#include "linklabel.h"
#include <QtWidgets>
LinkLabel::LinkLabel(QWidget * parent)
:QLabel(parent)
{
connect( this, SIGNAL( clicked() ), this, SLOT( slotClicked() ) );
}
void LinkLabel::slotClicked()
{
qDebug()<<"Clicked";
}
void LinkLabel::mousePressEvent ( QMouseEvent * event )
{
emit clicked();
}
#ifndef LINKLABEL_H
#define LINKLABEL_H
#include <QLabel>
class LinkLabel : public QLabel
{
Q_OBJECT
public:
LinkLabel(QWidget * parent = 0 );
~LinkLabel(){}
signals:
void clicked();
public slots:
void slotClicked();
protected:
void mousePressEvent ( QMouseEvent * event ) ;
};
#endif // LINKLABEL_H
/**
this is a QMainWindow using LinkLabel.
label is declared in the ui file (not included) and when a user click on the url shown, the application opens such url and
closes.
**/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "linklabel.h"
#include <QDesktopServices>
#include <QUrl>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->label->setText("<a href=\"http://localhost:8000\">Click me!</a>");
ui->label->setAlignment(Qt::AlignCenter);
ui->label->setOpenExternalLinks(false);
connect(ui->label, SIGNAL(linkActivated(QString)), this, SLOT(on_label_clicked(QString)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_label_clicked(const QString url)
{
qDebug("bang!");
QDesktopServices::openUrl(url);
close();
}
@ixxra
Copy link
Author

ixxra commented Jun 12, 2014

@jjfajardo note that if you would want to delegate the window closing to LinkLabel, what you have to do is to add the on_label_clicked slot to your class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment