Reputation: 107
I've got the following code:
void Test1::on_pushButton_1_clicked() // print the information
{
QPrinter printer(QPrinter::HighResolution);
printer.setCreator("Me");
printer.setDocName("Print");
printer.setPaperSize(QPrinter::A4);
QPrintPreviewDialog *pd = new QPrintPreviewDialog(&printer);
connect(pd,SIGNAL(paintRequested(QPrinter*)),this,SLOT(print(QPrinter*)));
pd->exec();
}
void Test1::print(QPrinter *p)
{
QPainter painter(p);
painter.setPen(Qt::blue);
painter.setRenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing |
QPainter::SmoothPixmapTransform, true);
painter.drawText(100, 100, "Name: ");
painter.drawText(300, 100, "SuperMan");
}
It works in my experimental projects, which are with 1 class [ 1 dialog ] only, but in my main project, when i press the button, the preview starts successfully, but then when i do press the "Print" button, my program just crash. It says "Your program stopped working, windows will search for solution" or something like that. I need to say that my program has a lot of classes and dialogs. I am almost sure that there is a problem with the pointers. I don't have lot of experience, so i just can't find where my mistake is. Please look my code and tell me what should i do because i've got only 2 more days to finish that project. Thank you a lot in advance.
Upvotes: 0
Views: 2108
Reputation: 107
Thanks to all for your answers, finally i've solved my problem.So how did i solved it? I've just changed Release mode to Debug mode. Tadaaam. Thats it. The file is a bit more bigger, but who cares. Everything works excellent. Thanks a lot for your answers again.
Upvotes: 0
Reputation: 21230
I think the reason is that you create your printer object in the stack
[..]
QPrinter printer(QPrinter::HighResolution);
[..]
and pass the pointer to it to the print preview dialog. As soon as dialog is running with exec()
your printer object still alive, however when you close the dialog, you exit from Test1::on_pushButton_1_clicked()
function, so the printer object got destroyed. Further reference to it leads to crash.
As a solution try to create your printer from heap like:
void Test1::on_pushButton_1_clicked() // print the information
{
// This printer should be deleted later.
QPrinter *printer = new QPrinter(QPrinter::HighResolution);
printer->setCreator("Me");
printer->setDocName("Print");
printer->setPaperSize(QPrinter::A4);
QPrintPreviewDialog *pd = new QPrintPreviewDialog(printer);
connect(pd, SIGNAL(paintRequested(QPrinter*)), this, SLOT(print(QPrinter*)));
pd->exec();
}
Upvotes: 1
Reputation: 4335
Think of the flow of this program and you'll see why it doesn't work.
print
slot now has invalid memory space where the QPrinter*
used to be and crashes your whole program.In Qt, most everything should be allocated on the heap for exactly this reason.
Upvotes: 0