-1

Using C++ as the language in Qt Creator I created a notepad (same as the simple text-editor for Microsoft Windows which is a basic text-editing program) but I could not find the exact code for its printing option to save as an image or pdf file and print what writes in the created notepad. Written code gives an error saying

...\NotePad\mainwindow.cpp:5: error: QPrinter: No such file or directory
 #include <QPrinter>

code written

#include <QPrinter>
void MainWindow::on_actionPrint_triggered()
{
    QPrinter printer(QPrinter::HighResolution);
    printer.setOutputFileName("print.ps");
    painter.end();
}
  • 3
    Isn't it a bit cruel to know the error and not share it with us? " gives an error"does not help at solving your issue. Also is `painter.end()` intended, a typo in the actual code or a typo here? – stefaanv Dec 21 '16 at 08:58
  • Edited the question – Chum_ ChumZy Dec 21 '16 at 09:16
  • For not finding QPrinter include file, see if this link helps: http://stackoverflow.com/questions/19145763/qt-cannot-open-include-file-qprinter – stefaanv Dec 21 '16 at 09:57

1 Answers1

3

You could use QTextDocument for a simple printing task like that. Assuming that you have loaded your text into it, you can do the following (I'm using printing to pdf just as an example, you can print wherever you want):

QTextDocument doc; // your text is here
QPrinter printer;
printer.setOutputFileName("<your_file_name_goes_here");
printer.setOutputFormat(QPrinter::PdfFormat);
doc.print(&printer);
printer.newPage(); // this might not be necessary if you want just 1 page, I'm not sure

If you want to use a QPainter, you should

QPrinter printer;
// setup the printer
QPainter painter;

if(!painter.begin(&printer))
{
   // return, throw exception, whatever
}
painter.drawText(10, 10, "your_text");
printer.newPage(); // Again, this might not be necessary if you want just 1 page, I'm not sure
painter.end();
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • @Chum_ChumZy, it draws "your_text" in a position with (10,10) coordinates. `QPrinter` is derived from `QPaintDevice`, so you can paint on it with a `QPainger` exactly the same way as you can print on anything else (like `QImage`). – SingerOfTheFall Dec 21 '16 at 09:19
  • would you mind explaining what does painter.drawText(10, 10, "your_text"); mean? I am looking for print option code fyi :) – Chum_ ChumZy Dec 21 '16 at 09:20
  • i want to print what is written in the created note pad using Qt. Not what the console shows :) – Chum_ ChumZy Dec 21 '16 at 09:24
  • @Chum_ChumZy, it has nothing to do with the console... you should read the documentation about `QPainter` if you want more info. For your case, the first example with `QTextDocument` should suffice. – SingerOfTheFall Dec 21 '16 at 09:27