2

QUrl class can be used to open both local or online file. I used QLineEdit to take URL as QString and give it to QUrl. The program can access both local and online file. My point question is: is there any official way to automatically detect if the given url is local or online and add http:// automatically if the url is online?

For example, if user type www.google.com, it should be online and should be added http:// before it being processed. If user type /home/username/somepath it should be offline.

Of course a little if and else thing with string pattern check can be used for this purpose. My question is, if there's officially supported way to do something like this from Qt5.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Mas Bagol
  • 4,377
  • 10
  • 44
  • 72

1 Answers1

4

You can use QUrl:fromUserInput(...) for that purpose.

QString first("qt-project.org");
QString second("ftp.qt-project.org");
QString third("hostname");
QString fourth("/home/user/test.html");

qDebug() << QUrl::fromUserInput(first);   // QUrl( "http://qt-project.org" )       
qDebug() << QUrl::fromUserInput(second);  // QUrl( "ftp://ftp.qt-project.org" )    
qDebug() << QUrl::fromUserInput(third);   // QUrl( "http://hostname" )             
qDebug() << QUrl::fromUserInput(fourth);  // QUrl( "file:///home/user/test.html" ) 
Dávid Kaya
  • 924
  • 4
  • 17
  • this answer has small shortage. It would be better to mention that local url can be queried by `isLocalFile()` like this: `if (QUrl::fromUserInput(file).isLocalFile()) { /*...do something...*/}` – S.M.Mousavi Jul 04 '22 at 11:33