ChatGPT解决这个技术问题 Extra ChatGPT

How to open a link in a default user browser in Qt?

I wonder how to open a link in a default user browser using Qt (that would open it across all platforms (Win Mac Lin))?


F
ForestPhoenix

In the doc: QDesktopServices

http://doc.qt.io/qt-4.8/qdesktopservices.html#openUrl

bool QDesktopServices::openUrl ( const QUrl & url ) [static]

Opens the given url in the appropriate Web browser for the user's desktop environment, and returns true if successful; otherwise returns false.


It doesn't work to put a string directly as an argument to that function. To open a URL from a string, you need to use the QUrl() function like this: openUrl (QUrl("http://stackoverflow.com/"));
Where does my answer suggest to use a string directly? You can see it says it needs a Url object to be passed.
I know. I just posted that comment to help people understand that. When I first saw it, I thought I had to use a string directly and it took some time before I understood that wasn't the case. I just wanted to help other people who would think the same thing.
For some reasons it doesn't work if the link contains an anchor, e.g. doc.qt.io/qt-5/qwidget.html#QWidget
T
Tan Viet

You can try this code

QString link = "http://www.google.com";
QDesktopServices::openUrl(QUrl(link));

Read QDesktopServices and QUrl to get further information.


No, this is actually the single proper SO-style answer with the working example how openUrl works. No need to go elsewhere and check specs.
Don't forget to add #include <QDesktopServices> to the top of your file
Think this is the better answer. Copy & paste – just works, thanks!
N
Nathan Boyd

you are looking for openUrl() in the desktop services class

http://qt-project.org/doc/qt-4.8/QDesktopServices.html