store input of line edit to string qt - c++

I'm a beginner.I am making a simple gui program using qt in which you enter a url/website and that program will open that webpage in chrome.I used line edit in which user enters url and i used returnPressed() slot, but the problem is (it might sound stupid) that i don't know how to take the input by user and store it in a string so that i can pass that string as parameter to chrome.Is im asking something wrong.also tell me how can i save input to a txt file, i know how to do that in a console program.Is this process is same with others like text edit etc.
My mainwindow.cpp:
QString exeloc = "F:\\Users\\Amol-2\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";
void MainWindow::on_site_returnPressed()
{
QString site;
getwchar(site);
QString space=" ";
QString result = exeloc + space + site;
QProcess::execute(result);
}
What im doing wrong.
thanks

You've got your approach slightly wrong, I can see where you're coming from though. It's actually a lot more simple than you're trying, Qt has a QDesktopServices class that allows you to interact with various system items, including open urls in the browser. There's documentation on it here.

QLineEdit has a text() function that will return a QString. So you can do something like this:
QString site = ui->site->text();
You don't have to use QProcess to open a web site in a browser. You can use QDesktopServices::openUrl static function.
Like this:
QString site = ui->site->text();
QUrl url(site);
QDesktopServices::openUrl(url);
Remember to include QDesktopServices and QUrl headers:
#include <QDesktopServices>
#include <QUrl>

Related

Directly executing a batch through clicked function in qt

So I'm trying to have my "button" directly execute a Batch file, important here is that I don't want it to show me a dialogue and make me chose the path, which is the problem I'm having right now with the following code
void MainWindow::on_pushButton_clicked()
{
QString filename=QFileDialog::getOpenFileName(
this,
tr("Open File"),
"C://",
"All files (*.*);;Text File (*.txt);;Music file (*.mp3)");
}
I think this is probably really simple, but i can't get it, I'm not even learning c++ at the moment but my boss asked me to create something out of my scope (wants me to create a GUI for a batch file and have them interact) and I thought of this approach, which is just creating a GUI that executes it.
I've looked at this question: asked to execute an external program with Qt
but they don't talk about how the file path can directly be added into the code, or if I should even be using Qprocess and how, and if I can pass it through "clicked" function.
I'm really inexperienced, all of the code above I got with the help of the internet, but I really don't know how to program using c++
so could someone please be kind enough to show me how a file path can be added to the code, assuming it's in C:\Users\name_goes_here\Downloads
I'd really appreciate it :D
I'd recommend using QProcess for anything "execute external program" with Qt.
You could do it like this:
void MainWindow::on_pushButton_clicked()
{
QProcess process;
process.start("C:/Users/name_goes_here/Downloads/yourfile.bat");
process.waitForFinished(); // Assuming that you do want to wait for it to finish before the code execution resumes
}
Note the "/" in the path. Only Windows uses the messed up "\" for path separation, which would require you to write "C:\\Users\\.." in any string in C++ as "\" needs to be escaped.
Luckily, Qt uses "/" as the universal separator and translates it to whatever the OS needs as required. So you should just use "/" whenever working with Qt.
This is from the Qt documentation:
Qt uses "/" as a universal directory separator in the same way that "/" is used as a path separator in URLs. If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system.
And finally, if you don't know how to code in C++, shouldn't you be learning that first instead of trying to execute batch files from within a library as complex as Qt? Sounds like you're trying to do too many new things at once.
This is fairly simple merging your source and the one you linked:
void MainWindow::on_pushButton_clicked()
{
QProcess::execute(
QString::fromLatin1(
"cmd.exe /c C:\\Users\\name_goes_here\\Downloads\\file.bat"));
}
Notes:
I used QProcess::execute() instead of QProcess::start() to make things even simpler.
To achieve execution of the batch file, I pass it to cmd32.exe as this is the interpreter which is responsible.
As MCVE testQProcessBatch.cc:
// Qt header:
#include <QtWidgets>
void on_pushButton_clicked()
{
#if 0 // WORKS:
QProcess::execute(
QString::fromUtf8("cmd.exe /c C:\\Users\\Scheff\\Downloads\\testBatch.bat"));
#else // WORKS AS WELL:
QProcess::execute(
QString::fromUtf8("C:\\Users\\Scheff\\Downloads\\testBatch.bat"));
#endif // 0
}
int main(int argc, char **argv)
{
qDebug() << "Version:" << QT_VERSION_STR;
// main application
QApplication app(argc, argv);
QMainWindow qWin;
QPushButton qBtn(QString::fromLatin1("Start cmd"));
qWin.setCentralWidget(&qBtn);
qWin.show();
QObject::connect(&qBtn, &QPushButton::clicked,
&on_pushButton_clicked);
// run application
return app.exec();
}
and the test batch file testBatch.bat:
echo "This is testBatch.bat"
pause
Tested with VS2013 on Windows 10:
Thanks for contributing guys!
I tried using the QProcess method but I think I'm too inexperienced when it comes to figuring out problems associated with it (which I did face when using this method). the CMD route is probably good but I also thought it was too difficult and both of these methods didn't work for me.
Here's what I have now (thanks to Detonar and ymoreau) and and it seems to be doing the job, this might not be the most optimal approach, but it worked for me!
I included QDesktopServices and QUrl
void MainWindow::on_pushButton_clicked()
{
QString filename="C:\\Users\\Name_goes_here\\Downloads\\test.bat";(
this);
hide(); //optional
QDesktopServices::openUrl(QUrl("file:///"+filename,QUrl::TolerantMode));
}

QWebEngine: print a page?

The migration from QWebKit to QWebEngine seems to be much more complicated than Qt guys claimed. With QWebKit I could print a webpage easily via
QWebView->print(&printer);
With QWebEngine class QWebEngine view does not provide a method print(). Their browser example uses a class named QWebEngineFrame which offers a method print() - but the whole QWebEngineFrame is not defined anywhere!
So my question: how do I print a page using QWebEngine?
I think the correct way to use QWebEngineView::render method because QWebEngineView is a QWidget. It accepts paint device as a first argument and you may pass QPrinter there for printing.
Update: If you can use the latest version of Qt, in Qt 5.8 a new function for printing page was added:
void QWebEnginePage::print(QPrinter *printer, FunctorOrLambda resultCallback);
Actually it first prints to temp PDF with QPrinter settings.
Here is the link to Qt docs.
You can read about this in our blog also.
I would offer following code (for a while):
QTextEdit *textEdit = new QTextEdit;
ui.myWebView->page()->toHtml([textEdit](const QString &result){ textEdit->setHtml(result); });
textEdit->print(somerinter);
textEdit->deleteLater();
Qt 5.7 includes print support in to pdf files for QWebEngine.
Use printToPdf function to export the current page in a pdf file. Example:
const QString fileName = QFileDialog::getSaveFileName(0,
tr("Save pdf"),
".",
tr("PDF Files (*.pdf)"));
if (fileName.isEmpty()) {
return;
}
ui->webView->page()->printToPdf(fileName);
QWebView->page()->print(&printer, [=](bool){});

Saving the content of a QLineEdit object into a string variable (C++)

I've looked around the Qt Documentation, but within my project, I'd like to having most of the non-graphical 'more thinking' part of my program be on a seperate .cpp file.
Given that, I was wanting to take the text typed into a QLineEdit object and save it as a string after the user triggers the 'returnPressed' action, but when I type:
void MainWindow::on_lineEdit_returnPressed()
{
QMessageBox msgBox;
msgBox.setText("The entry has been modified.");
msgBox.exec();
//The line which should save the contents of the QLineEdit box:
string input = QLineEdit::text();
}
...Into the template provided by the Qt Creator IDE (with all necessary slots hopefully created) The compiler returns
In member function 'void MainWindow::on_lineEdit_returnPressed()'
cannot call member function 'QString...'
... and so on.
How should I rewrite my code to do this correctly?
You must choose how to store the string. Your main options are: array of chars, std::string from the standard library, and QString from Qt. If you need to use the string in a third party library then you might need to store it in an std::string or an array of chars, but if that's not the case then I suggest that you simply use QString as it is widely used throughout Qt, although you can convert a QString to std::string or array of chars.
You must actually retrieve the text. To do this you must call the text() function on the QLineEdit instance, not on the QLineEdit class itself. All widgets can be accessed through the ui pointer. Open the designer and check the name of the line edit, the default name is lineEdit, so try replacing the line
string input = QLineEdit::text();
with the line
QString input = ui->lineEdit->text();
How about that:
lineEdit->text().toStdString()
For Qt6 this is the best solution that I found
string input = ui->lineEdit->text().toStdString();
A more developed answer from 'alagner'

qt5 designer, using fileopen, displaying file path in lineedit, is there an issue doing it this way?

just started using qt,
looked through docs, google, examples, etc.. trying to find simple examples(working mind you)
that showed how to do (imho) simple things, by themselves.
well i stumbled upon my answer and i was wondering if this approach would cause an issue later as the code becomes more complex.
there are more includes than needed for this example, but this is direct from working code.
mainwindow.h:
i added
private slots:
void vpkButton_clicked();
and after
Ui::MainWindow *ui;
i added
QLineEdit *vpkPathTxt;
in mainwindow.cpp:
after
ui->setupUi(this);
i added
connect( this->ui->vpkButton, SIGNAL( clicked() ), this, SLOT(vpkButton_clicked()) );
to connect my ui button to the proper slot, the issue was getting the string from vpkButton_clicked() to display in the line edit i made in the designer,
what ended up working for me was adding this next:
vpkPathTxt = this->ui->vpkPathTxt;
the function in my main.cpp became very easy:
(QString declarations at top outside voids)
void MainWindow::vpkButton_clicked()
{
vpkName = QFileDialog::getOpenFileName(this,
tr("Open VPK File"), "~/", tr("VPK Files (*_dir.vpk)"));
vpkPathTxt->setText(vpkName);
qDebug() << vpkName;
}
the reason i am ask is because it seems a little too easy to be reliable, and the fact that i havent seen it done like this,
any input welcome
thankyou
One problem with your slot is that you don't consider the case where the user discards the "open file" dialog. In this case, the function QFileDialog::getOpenFileName returns a null QString, so you should only proceed with your logic if the return value was not a null string:
if (!vpkName.isNull()) {
...
}
The second problem is as follows and I made some assumptions since I don't see your full code:
I guess you want to load a file using the file name the user has chosen in the dialog. But you set the file name in the line edit too, which the user can edit by hand. I also guess that the actual file loading happens in a different step (i.e. after clicking another button), so after the user has edited the file name by hand in the line edit it won't be the same than in your local variable vpkName.
When loading the file I'd read the contents of the line edit instead of the variable vpkName so the edit made by hand will be respected.
A different method is to also watch for editing of the line edit and reflect the changes in your variable too. Then it will be ok to read the variable instead of the line edit when loading the file later on.

QWebView with multiple frames/pages sharing the same session data

I have a QWebView, and it loads a certain page, the user logs in and goes about his business. This all works fine.
What I would like to do is have a second frame/pae open, that uses the logged in users session and all that jazz to load a reports page that it will render to an image file for display on a little USB screen.
Right now, I accomplish this with a completely different webView, which can't access protected pages, which is a bit of a security risk.
Here is some pseudo code for what I am thinking of:
webView->mainFrame->loadNormalUrl
secretFrame = webView->createSecretFrame
secretFrame->useSessionOf(webView->mainFrame)
secretFrame->loadReportUrl
secretFrame->doStuffThatAlreadyWorks
Any help, pointers, links would be super helpful! Thanks :)
Well,
This question didn't receive and answer, so I pattered off to the qtwebkit mailing list, and they were very helpful.
The essential thing is to subclass QNetworkCookieJar, the most important method being the loading from disk, which you call in your constructor.
QList<QNetworkCookie> cookies;
if (m_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&m_file);
QString txt = in.readAll();
QStringList lines = txt.split("\n");
foreach (QString c, lines) {
cookies.append(QNetworkCookie::parseCookies(c.toUtf8()));
}
m_file.close();
}
setAllCookies(cookies);
Of Course, you'll also need a writing function, like so:
QTextStream out(&m_file);
foreach (const QByteArray &cookie, m_rawCookies)
out << cookie + "\n";
m_file.close();
And your raw cookies like so:
QList<QNetworkCookie> cookies = allCookies();
m_rawCookies.clear();
foreach (const QNetworkCookie &cookie, cookies) {
m_rawCookies.append(cookie.toRawForm());
}
If you download the webkit source, you can take a look at the testbrowser code for a more complete example.
One way you could approach this is to not try to do it with QWebViews at all, but instead subclass QNetworkManager and hook its signals to snoop the QNetworkReplys that are sent back.
Otherwise in your second QWebView you could just set its content to the HTML you want to display and you might be able to enforce only grabbing data from the cache.