QMessageBox - url encoding/decoding - c++

I created a QMessageBox with an html link:
QTMessageBox msgBox(Utility::UI::topLevelWidget());
msgBox.setText("Link");
msgBox.exec();
If I left click the link a new web browser tab opens. The problem is that the url http://www.example.cz/?url=www**%2525**www is opened instead of http://www.example.cz/?url=www**%25**www
How do I prevent such behavior?
UPDATE: If I right click the link, choose "Copy link" and paste it into the browser, the link is ok.

That's because % has the html encoding %25. So %25 -> %2525.
Why does Qt encode the links automatically?
In the QMessageBox, there is a QLabel. The label uses the Qt::TextFormat Qt::AutoText by default. Therefore, it detects in your text, that it is html encoded and generates the link.
The QLabel sends the signal linkActivated(const QString& link) or uses QDesktopServices::openUrl(), depending its the boolean openExternalLinks.
It seems, that the QMessageBox sets openExternalLinks to true.
Since the link will be used as input for a QUrl, it will be parsed. That's the reason for the double encoding.
It is possible, to modify the behavior of QDesktopServices::openUrl() by using its static method void QDesktopServices::setUrlHandler. I implemented and tested it for the desired behavior:
MyUrlHandler urlHandler;
QDesktopServices::setUrlHandler( "http", &urlHandler, "handleUrl" );
QMessageBox msgBox;
msgBox.setText( "Link" );
msgBox.show();
Using the class MyUrlHandler:
class MyUrlHandler : public QObject
{
Q_OBJECT
public:
MyUrlHandler(QObject* parent=0):QObject(parent){}
public slots:
void handleUrl(const QUrl &url)
{
QDesktopServices::openUrl( QUrl::fromEncoded( url.toString().toAscii() ) );
}
};
The trick is simple, I set the link address directly to the QUrl instance as already valid url.
But unfortunately, it modifies the behavior globally.

Related

How to add hyperlinks in Qt without QLabel?

I have some labels and layouts nested inside a QWidget to build a part of a sidebar. Each QWidget is its own section and one component currently looks like this:
To my understanding, you can only set hyperlinks with QLabel, but I'm trying to get the whole area between the white lines clickable. This is including the icon and the whitespace. Is there any way to achieve this?
This got marked as a duplicate to the opposite of what I was asking, so I'd like to reiterate that I'm trying to implement a hyperlink without QLabel.
You can easily have a widget open a link on click:
class Link : public QWidget {
Q_OBJECT
public:
Link(QUrl url, QWidget p = nullptr) : QWidget(p), _url(url) {}
QUrl _url;
void mouseReleaseEvent(QMouseEvent *) { QDesktopServices::openUrl(_url); }
}
You can avoid any extra signals and connections, and have each link widget store its own link internally, the url can be set on construction and changed at any time. Not using signals and slots makes it easier to change the link too, without having to disconnect previous connections.
IMO going for a signals and slots solution is only justified when you want different arbitrary behavior. In this case you always want the same - to open a particular link, so you might as well hardcode that and go for an easier and more computationally efficient solution.
I would just manually catch the SIGNAL for clicked() and use desktop services to open the url in code.
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.
http://doc.qt.io/qt-4.8/signalsandslots.html
Using this type of syntax, or in the designer, you can also connect a signal to a slot.
connect(widgetThatRepresentsURL, SIGNAL(clicked()),
handlerThatWillOpenTheURL, SLOT(clicked_on_url()));
For widgets that don't have a signal set up for clicked (or whatever event you are interested in), you can subclass the widget in question and reimplement...
void QWidget::mousePressEvent ( QMouseEvent * event ) [virtual protected]
Specifically for creating a signal, there is emit. I've used this in the past like the following
void Cell::focusInEvent(QFocusEvent *e)
{
emit focus(this, true);
QLineEdit::focusInEvent(e);
}
with the following in the header
signals:
void focus(Cell *, bool);

qlabel mailto link in Qt 4.8.6

I've followed instructions given on previous questions like this
so now if I put a link to a regular page it opens fine with the default browser. But if I want to open a mailto link from QT QLabel 4.8.6 the link does nothing.
What am I doing wrong?
here is the code:
UpgradeMessageDialog* umd = new UpgradeMessageDialog();
umd->ui->label->setOpenExternalLinks(true);
umd->ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
umd->exec();
umd->ui->label->connect(umd->ui->label,
SIGNAL(linkActivated(const QString&)), umd,
SLOT(linkOpen(const QString&)));
(this is defined as a public slot in the appropriate h file)
void UpgradeMessageDialog::linkOpen(const QString &link)
{
QDesktopServices::openUrl(QUrl(link));
}
Just to clarify: I have a default mail program set up in my computer, and when I type mailto:a#b.c in the browser that program opens fine.
First, there are two ways to handle link activation in QLabel. You should use one of them, but I see you are trying to use both.
This two ways are:
Call openExternalLinks(true), so that QLabel will automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated() signal.
Connect to the linkActivated() signal and then manually open link in the connected slot (by calling QDesktopServices::openUrl() for example).
Also you use the exec() function wrong. You should put the exec() call after the connect() call, because exec() is blocking so the signal connection will actually happened after the dialog is closed.
So your code should be like this:
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
connect(umd->ui->label, SIGNAL(linkActivated(QString)), umd, SLOT(linkOpen(QString)));
umd->exec();
or like this:
umd->ui->label->setTextFormat(Qt::RichText);
umd->ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
umd->ui->label->setOpenExternalLinks(true);
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
And a little advise: put the label initialization code into the UpgradeMessageDialog constructor.
UpgradeMessageDialog::UpgradeMessageDialog(QDialog* parent) : QDialog(parent)
{
ui->label->setTextFormat(Qt::RichText);
ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
ui->label->openExternalLinks(true);
ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
}
And then you can use your dialog this way:
QScopedPointer<UpgradeMessageDialog> umd = new UpgradeMessageDialog;
umd->exec();
#include <QUrl>
#include <QDesktopServices>
myLabel = new QLabel(this);
myLabel->setTextFormat(Qt::RichText);
myLabel->setText("Email:href='mailto:serge#essetee.be'>serge#essetee.be</a>");
myLabel->setOpenExternalLinks(true);
Now you just have to click the link and the standard mail client will be launched.

Link clicked signal QWebEngineView

We already have QWebView implementation and now we want to migrate to QWebEngineView.
Through QWebView we have registered below signal to receive notification for any link is clicked on webview or not and we are getting signal in QWebView.
connect(m_WebView, SIGNAL(linkClicked(const QUrl &)),SLOT(urlLinkClicked(const QUrl &)));
In "urlLinkClicked" slot, we are opening new tab and open that URL into new tab.
We are facing some issue with QWebEngineView. As there is no such signal "linkClicked" exist in QWebEngineView. So we have tried below options but still not able to find the solution.
In main class, we have created WebEngineView class instance and setting WebEnginePage. We are able to render the website in view class but when we click on any link then we are not getting any signal so we are not able to open that new website in new tab.
m_WebEngineView = new QWebEngineView(this);
m_WebEngineView->setPage(new QWebEnginePage());
We have also override "acceptNavigationRequest" method to get the link clicked event in mainWebEngineView but we are not able to get the link clicked event.
Any suggestion i can try ?
Thanks in Advance.
Override QWebEnginePage::acceptNavigationRequest in QWebEnginePage subclass:
bool MyWebPage::acceptNavigationRequest(const QUrl &url, NavigationType type, bool isMainFrame)
{
if (type == QWebEnginePage::NavigationTypeLinkClicked)
{
qDebug() << url;
}
return true;
}
use this in inherited WebEngineView and in inherited webpage we can find hoverdUrl
QWebEngineView *WebEngineView::createWindow(QWebEnginePage::WebWindowType type)
{
if(type==QWebEnginePage::WebBrowserTab)
{
if(!hoverdUrl.isEmpty())
QDesktopServices::openUrl(QUrl(hoverdUrl));
qGlobalDbg("Open external Url requiested in chat, url : " + hoverdUrl, toKIBANA|toLOG);
}
//qDebug()<<"============== link Clicked "<<hoverdUrl;
return NULL;
}
I think you could use the signal "urlChanged".
See the header "Signals" on there official documentation page.
http://doc.qt.io/qt-5/qwebengineview.html
If this does not help I need to know what version of the Qt framework you are using.
Best Regards
/ Rasmus
Unfortunately urlChanged signal that QWebenginePage has emits only when url of current page is changed. Previous linkClicked signal was also emitted when url of current page was not changed. There is a way to handle this, but you would need to have access to page source code.
This functiionality is achieved through QWebChannel class. You would need to create webChannel object and a special callback class, which would handle call backs from webpage in a way you like. Then you would need to set this webChanell on a page you want to and do all the connections like this:
MyCallBackObject* callback= new MyCallBackClass();
mWebChannel = new QWebChannel(this);
mWebChannel->registerObject(QStringLiteral("MyCallBackObject"), callback);
mWebView->page()->setWebChannel(mWebChannel); // mWebView is QWebEngineView
connect(callback, SIGNAL(urlChanged(QUrl)),
this, SLOT(linkClickedSlot(QUrl))); // connect statement, urlChanged is defined in your callback class, linkClickedSlot is a slot where you process clicked signal
For more reference - please use official example from qt or the one from kdab or this video from Qt Developer Days conference

Close QFileDialog only when click "open"

Whenever I select a file in my QFileDialog the accepted signal is fired and the window closes. I want to keep the window open so I can select multiple files and then capture the signal fired when "open" is clicked.
QFileDialog* myDialog = new QFileDialog(this);
myDialog->setFileMode(QFileDialog::ExistingFiles);
myDialog->setVisible(true);
What signals should I be connecting here to achieve this effect?
The QFileDialog::ExistingFiles should guarantee that multiple files can be selected. Given that, you can connect to the signal:
void QFileDialog::filesSelected(const QStringList & selected)
Directly from the documentation:
When the selection changes for local operations and the dialog is accepted, this signal is emitted with the (possibly empty) list of selected files.
However, if you are only interested in collecting such files, you can totally avoid signal-slot and write (taken again from the documentation):
QStringList fileNames;
if (dialog.exec())
fileNames = dialog.selectedFiles();
Note that in this case dialog object has been created on the stack (which is the common approach for such objects).
Your code looks fine to me. I believe you are double clicking on the file inside the dialog instead of holding on the Ctrl and single clicking on all the files you need.
You can optionally use an event filter and ignore the double click event.
Once you click on Open, you can get a list of all the file paths in the QStringList given by QFileDialog::selectedFiles(). Also it's better to use a stack variable here and use exec method to launch it as pointed out by BaCaRoZzo.
QFileDialog myDialog(this);
myDialog.setFileMode(QFileDialog::ExistingFiles);
if(myDialog.exec())
{
qDebug() << myDialog.selectedFiles();
}
Whenever I select a file in my QFileDialog the accepted signal is fired and the window closes. I want to keep the window open so I can select multiple files
All other answers is just solution for selection many files one time and CLOSE window after Open button pressing. Get my solution, it is not very simple because it required lot of work:
I used lamda expressions and new signals and slots syntax in my answer, but you can use old syntax or add
CONFIG += c++11
to the .pro file and use lambdas.
Subclass QFileDialog:
Header:
#ifndef CUSTOMFILEDIALOG_H
#define CUSTOMFILEDIALOG_H
#include <QFileDialog>
#include <QDebug>
class CustomFileDialog : public QFileDialog
{
Q_OBJECT
public:
explicit CustomFileDialog(QWidget *parent = 0);
void setDefaultGeo(QRect);
signals:
void newPathAvailable(QStringList list);
public slots:
private:
bool openClicked;
QRect geo;
};
#endif // CUSTOMFILEDIALOG_H
When you click open, you hide your dialog, not close! Cpp:
#include "customfiledialog.h"
CustomFileDialog::CustomFileDialog(QWidget *parent) :
QFileDialog(parent)
{
openClicked = false;
connect(this,&QFileDialog::accepted,[=]() {
openClicked = true;
qDebug() << openClicked;
this->setGeometry(geo);
this->show();
emit newPathAvailable(this->selectedFiles());
});
}
void CustomFileDialog::setDefaultGeo(QRect rect)
{
geo = rect;
}
Usage:
CustomFileDialog *dialog = new CustomFileDialog;
QStringList fileNames;
dialog->setFileMode(QFileDialog::ExistingFiles);
dialog->show();
dialog->setDefaultGeo(dialog->geometry());
connect(dialog,&CustomFileDialog::newPathAvailable,[=](QStringList path) {
qDebug() << path;
});
Why do you need setDefaultGeo? Without this method, your window will move after Open pressing.
What we get?
I open filedialog and select two files:
I clicked Open, but window didn't close! You can choose new files again and again!
One more file and so on:
Window will closed only when user press Close button, but you will have all path which user choose.
As you said:
I want to keep the window open so I can select multiple files
You get this.
I don't think anyone has understood the question (or it could be just me looking for my own solution)...
I had the same issue. As soon as I clicked a file the dialog would close. I couldn't ever select a file and then click "Open" because the dialog instantly closed as soon as I single clicked a file.
related: qtcentre.org/threads/48782-QFileDialog-single-click-only
It turns out it was my linux os settings (under mouse). File opening was set to single-click. I still feel like something external might have toggled this but that is just speculation. It appears Qt was going the right thing. Check another application, like kate on KDE and see if it has the same behavior. That is what clued me in to the source of my issue.

Modifying QFileDialog::getOpenFileName to have an additional drop down

I am a student programmer using Qt to build a reader Table for my company. This reader is both an editor and converter. It reads in a .i file allows table editing of a text document and then puts out a .scf file which is essentially a separated value file stacked under a legend built with headers. I digress... Basically the file format imported is really hard to scan and read in(mostly impossible) so what I'd like to is modify the open file preBuilt QFileDialog to include an additional drop down when older file types are selected to declare their template headers.
When the user selects .i extension files(option 2 file type) I would like to enable an additional drop down menu to allow the user to select which type of .i file it is(template selected). This way I don't have to deal with god knows how many hours trying to figure out a way to index all the headers into the table for each different type. Currently my importFile function calls the dialog using this:
QString fileLocation = QFileDialog::getOpenFileName(this,("Open File"), "", ("Simulation Configuration File(*.scf);;Input Files(*.prp *.sze *.i *.I *.tab *.inp *.tbl)")); //launches File Selector
I have been referencing QFileDialog Documentation to try and find a solution to what I need but have had no avail. Thanks for reading my post and thanks in advance for any direction you can give on this.
UPDATE MAR 16 2012;
First I'd like to give thanks to Masci for his initial support in this matter. Below is the connect statement that I have along with the error I receive.
//Declared data type
QFileDialog openFile;
QComboBox comboBoxTemplateSelector;
connect(openFile, SIGNAL(currentChanged(const &QString)), this, SLOT(checkTemplateSelected()));
openFile.layout()->addWidget(comboBoxTemplateSelector);
I also noticed that it didn't like the way I added the QComboBox to the modified dialog's layout(which is the second error). I really hope that I'm just doing something dumb here and its an easy task to overcome.
In response to tmpearce's comment heres my header code;
#include <QWidget>
namespace Ui {
class ReaderTable;
}
class ReaderTable : public QWidget
{
Q_OBJECT
public:
explicit ReaderTable(QWidget *parent = 0);
~ReaderTable();
public slots:
void checkTemplateSelected();
void importFile();
void saveFile();
private:
Ui::ReaderTable *ui;
};
Thanks for reading and thanks in advance for any contributions to this challenge!
Instance a QFileDialog (do not call getOpenFileName static method), access its layout and add a disabled QComboBox to it.
// mydialog_ and cb_ could be private fields inside MyClass
mydialog_ = new QFileDialog;
cb_ = new QComboBox;
cb_->setEnabled(false);
connect(mydialog, SIGNAL(currentChanged(const QString&)), this, SLOT(checkFilter(const QString&)));
mydialog_->layout()->addWidget(cb_);
if (mydialog_->exec() == QDialog::Accepted) {
QString selectedFile = mydialog_->selectedFiles()[0];
QString cbSelection = cb_->currentText();
}
the slot would be something like:
void MyClass::checkFilter(const QString& filter)
{
cb_->setEnabled(filter == "what_you_want");
}
returning from the dialog exec(), you could retrieve selected file and cb_ current selection.
Notice you could add something more complex than a simple QComboBox at the bottom of the dialog, taking care of gui cosmetics.
Actually I don't like very much this approach (but that was what you asked for :-). I would make a simple dialog like this:
and enable the combo only if the selected file meets your criteria. The "browse" button could call getOpenFileMethod static method in QFileDialog.
You can handle item selection by this signal:
void QFileDialog::fileSelected ( const QString & file )
Then it occurs, call setFilter with type you want.
Sorry, if i don't understand your task.