Print a textEdit in Qt - c++

How can I print the text available in a textEdit using Qt creator (C++)? Please help me with this. I created a note pad using a textEdit. Now I want to print the note pad content. That mean the text typed in textEdit. So please help me.
please mention header files that I need to include as well.
Here is something I tried previous. but it's not working. so please help me with this.
void MainWindow::on_action_Print_triggered()
{
QString textFromField = ui->txtEdit->toPlainText();
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFileName("print.ps");
QPainter painter;
painter.begin(&printer);
printer.newPage();
painter.end();
}

QTextEdit already has method which allows you print it's content, so you don't need QPainter. Use this (I printed pdf as example):
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("outputt.pdf");
ui->textEdit->print(&printer);
print()
And of course you need
#include <QPrinter>
but I think that it is already added in your project.

Related

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){});

Print the contents of QWebFrame with header and footer

I want to print a QWebView with a header and a footer. I'm using the class QPrintPreviewDialog to preview the print.
I saw how solve this issue the projects phantomjs and wkhtmltopdf but it seems a little excessive the need to include in my project a modified version of WebKit.
Apparentyly printing headers and footers with Qt and Webkit it's an issue not enterely solved:
https://bugs.webkit.org/show_bug.cgi?id=30357
https://bugreports.qt.io/browse/QTBUG-29619
https://wiki.qt.io/Qt_project_org_faq (Question 229)
A priori I don't know how many pages I am going to print. Currently I am subclassing QPrinter and reimplementing the newPage() method. It's an awful hack but nearly works. The issue i'm facing is that everything that it is printed outside the pageRect it is shown like blurred. The watermark effect is only present in the preview not in the printed result, but the low quaility is present always.
There is something i can do to print headers with better quality, without bring all WebKit to my project?.
The difference that I suspect is introducing the problem is that I use QWebView::render instead of QWebView::print. QCustomPrinter has an associated QPainter before printing the header ( the QPainter associated when the content was printed ). Therefore I can't invoke QWebVieww:print when printing the headers because that method tries to associate a new QPainter to QPrinter.
void CustomPrinter::printHeader()
{
QPainter & painter =*this->paintEngine()->painter();
QWebView v;
v.setContent("<html> "
"<body>"
" asdadasdasdasd "
"</body>"
"</html>");
v.setFixedSize(this->pageRect().size());
v.render(&painter,QPoint(0,- 95),QRegion(0,0,this->pageRect().width(),95));
}
EDIT (based on Kuba Ober answer):
Using QTextDocument instead of QWebView solves the quality issue.
void CustomPrinter::printHeader()
{
QPainter * painter =p->paintEngine()->painter();
painter->save();
QTextDocument v;
v.setHtml(QString::fromStdString(_impresion.cabecera()));
QRectF r =this->pageRect();
r.moveTo(0,0);
r.setHeight(95);
painter->translate(0,-95);
v.drawContents(painter,r);
painter->restore();
}
I share a minimun example of what i'm talking about. The CustomPrinter class prints the header.
https://www.dropbox.com/s/2vifzk8rs6scrx5/stackExample.tar.gz?dl=0

Can i read value from QLabel

I now how to set value(number) but can i read that label in some variable. if can't read, in which similar widgets can i put value and read it. Any help would be halpful or someone has an other idea. Maybe like LCD number, spin box
Like this?
QString text = someLabel->text();
Here is the documentation. QLabel.text()
EDIT:
QString text = theLabel.text();
//or with pointer
QString text = theLabel->text();
have you tried :
QString s = YourQLabel->text();
This should work, I guess.
// Thelepaty mode on
You need to use editor widgets, for example QLineEdit or QTextEdit. You may customize it via QSS to look like a QLabel.
P.S. try to improve your English. It is hard to understand, what you are asking.
// Thelepaty mode off

Detecting PDF Printing on Mac

I use a QPrintDialog to initialize a QPrinter object like this:
QPrinter printer;
QPrintDialog dlg(&printer);
if (dlg.exec() == QDialog::Accepted)
{
/* Are we printing to PDF? */
}
On Windows, it's easy to detect if the output is going to a file or to a PDF writer. On a Mac, none of the same functions work:
if ((printer.outputFormat() == QPrinter::PdfFormat)
|| (!printer.outputFileName().isEmpty()))
{
qDebug("PDF mode");
}
Looking at a copy of qprintdialog_mac.mm online, in the function QPrintDialogPrivate::closeCarbonPrintPanel(), Qt attempts to detect if the output is redirected to a file. It stores the file name in a member of QMacPrintEnginePrivate. Somehow that name never makes its way to the QPrinter object. I'm not sure where the disconnect is.
So..... how can I tell if the print output is actually going to a file? I'm willing to get platform specific here if it's easy. I have zero Mac programming experience though.
This was a bug in Qt.
In Qt 5.3 the sample code provided will work because of the second condition, the call to QPrinter::outputFileName().
As of Qt 5.14, the outputFileName property of QPrinter is still null, even if "Save as PDF" was selected in the QPrintDialog.
However, when painting to the QPrinter object, the right thing is done.
if "Open with Preview" was selected, the painted contents will open
in preview.
if "Save as PDF" is selected, a file dialog will pop up
if "Send in Mail" is selected, the mail client will open with the PDF
attaced
etc.
Somehow, the QPrinter seems to store all the info from the dialog in an opaque way not accessible through public getters.
The correct way to support all the options from the mac print dialog seems to be:
QPrinter printer;
QPrintDialog dlg(&printer);
if (dlg.exec() == QDialog::Accepted)
{
QPainter painter;
painter.begin(&printer);
// do the painting
painter.end();
}
Unfortunately, it does not seem possible to extract the info out of the QPrinter object in case you like to implement your own printing logic.

setCentralWidget() causing the QMainWindow to crash.. Why?

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
this->setupUi(this);
this->setupActions();
this->setWindowTitle(tr("CuteEdit"));
label = new QLabel(tr("No Open Files"));
this->setCentralWidget(label);
label->setAlignment(Qt::AlignCenter);
}
By above code, I get a GUI like this(Its a screenshot of whole screen, Only observe the window displayed in middle of page of ebook). (I used QT Designer)
Now, i want user to select File->Open.. A Dialog appears and file gets selected.. Its contents are to be displayed in *textEdit widget..
Function for that is below..
void MainWindow::loadFile()
{
QString filename = QFileDialog::getOpenFileName(this);
QFile file(filename);
if (file.open(QIODevice::ReadOnly|QIODevice::Text))
{
label->hide();
textEdit->setPlainText(file.readAll());
mFilePath = filename;
QMainWindow::statusBar()->showMessage(tr("File successfully loaded."), 3000);
}
}
The window crashes at line:-
textEdit->setPlainText(file.readAll());
But if i comment the line:-
this->setCentralWidget(label);
i mean i remove label as being the central widget, the program runs as expected.. Why?
And also, I am not clear about the concept of CentralWidget. Pls guide.
JimDaniel is right in his last edit. Take a look at the source code of setCentralWidget():
void QMainWindow::setCentralWidget(QWidget *widget)
{
Q_D(QMainWindow);
if (d->layout->centralWidget() && d->layout->centralWidget() != widget) {
d->layout->centralWidget()->hide();
d->layout->centralWidget()->deleteLater();
}
d->layout->setCentralWidget(widget);
}
Do you see that if your MainWindow already had centralWidget() Qt schedules this object for deletion by deleteLater()?
And centralWidget() is the root widget for all layouts and other widgets in QMainWindow. Not the widget which is centered on window. So each QMainWindow produced by master in Qt Creator already has this root widget. (Take a look at your ui_mainwindow.h as JimDaniel proposed and you will see).
And you schedule this root widget for deletion in your window constructor! Nonsense! =)
I think for you it's a good idea to start new year by reading some book on Qt. =)
Happy New Year!
Are you sure it's not label->hide() that's crashing the app? Perhaps Qt doesn't like you hiding the central widget. I use Qt but I don't mess with QMainWindow that often.
EDIT: I compiled your code. I can help you a bit. Not sure what the ultimate reason is as I don't use the form generator, but you probably shouldn't be resetting the central widget to your label, as it's also set by the designer, if you open the ui_mainwindow.h file and look in setupGui() you can see that it has a widget called centralWidget that's already set. Since you have used the designer for your GUI, I would use it all the way and put the label widget in there as well. That will likely fix your problems. Maybe someone else can be of more help...
I'm not sure I understood your problem, neither what the guys above said (which I guess are valid information) and it seems to be an old topic.
However, I think I had a problem that looks like this and solved it, so I want to contribute my solution in case it helps anyone.
I was trying to "reset" central widget using QLabels. I had three different ones, switch from first to second, then to third and failed to switch back to the first one.
This is my solution that worked:
Header file
QLabel *imageLabel;
Constructor
imageLabel = new QLabel("<img src='/folder/etc.jpg' />");
this->setCentralWidget(imageLabel);
Reset
imageLabel = NULL;
imageLabel = new QLabel("<img src='/folder/etc.jpg' />");
this->setCentralWidget(imageLabel);
Hope that helps
Aris