Search code examples
c++qtqt5qpushbuttonqdesktopservices

QDesktopServices::openUrl() not working Qt


This is my code:

QPixmap map(":/Medal.jpg");
QIcon ico(map);
ico.addPixmap(map);
QPushButton *p = new QPushButton;
p->setIcon(ico);
QString link = "http://www.google.com";
QObject::connect(p, SIGNAL(clicked()),window,SLOT(QDesktopServices::openUrl(QUrl (link))));

The pic is showing up but it is not opening the browser. Kindly help me out.


Solution

  • You have to use a lambda function:

    #include <QApplication>
    #include <QDesktopServices>
    #include <QPushButton>
    #include <QUrl>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QPushButton p("Click me");
        QString link = "http://www.google.com";
        QObject::connect(&p, &QPushButton::clicked, [&link](){
            QDesktopServices::openUrl(QUrl(link));
        });
        p.show();
    
        return a.exec();
    }
    

    or with std::bind()

    #include <QApplication>
    #include <QDesktopServices>
    #include <QPushButton>
    #include <QUrl>
    #include <functional>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QPushButton p("Click me");
        QString link = "http://www.google.com";
        QObject::connect(&p, &QPushButton::clicked, std::bind(QDesktopServices::openUrl, QUrl(link)));
        p.show();
    
        return a.exec();
    }
    

    note:

    you need to enable C++11 in Qt, for this review the following question: How to enable C++11 in Qt Creator?, which indicates that you add CONFIG += c++11 in your .pro