1

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.

eyllanesc
  • 190,383
  • 15
  • 87
  • 142

1 Answers1

2

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

eyllanesc
  • 190,383
  • 15
  • 87
  • 142
  • The first one is showing:F:\Projects\Calci\main.cpp:94: warning: lambda expressions only available with -std=c++11 or -std=gnu++11 [enabled by default] }); –  May 17 '18 at 05:03
  • The second one: F:\Projects\Calci\main.cpp:94: warning: lambda expressions only available with -std=c++11 or -std=gnu++11 [enabled by default] }); ^ –  May 17 '18 at 05:04
  • Last problem: As you know i have added an image so now it is showing F:\Projects\Calci\main.cpp:125: error: no matching function for call to 'QVBoxLayout::addWidget(QPushButton&)' lay->addWidget(p); –  May 17 '18 at 05:10
  • It is not showing properly so here is the link: http://www.mediafire.com/file/rz8l5qfr25j4i5q/main.cpp –  May 17 '18 at 05:18
  • The best answer. –  May 17 '18 at 05:24
  • @Coder7 Do not use pointers unnecessarily, it is bad programming practice, also read about http://doc.qt.io/qt-5/signalsandslots.html and https://wiki.qt.io/New_Signal_Slot_Syntax – eyllanesc May 17 '18 at 05:25