PDF printing on MAC does not work outside Qt creator?
-
I've created a plotting program and want to let the users to print on paper or PDF.
When I run my program from inside Qt Creator, PDF printing is ok.
However, if I create a bundle, printing from the bundle does not work!
The problem is that the painter does not begin with the printer (returns false)
I've made my tests using Qt 5.2.1.
I've created the bundle using the macdeployqt utilityA tiny program showing this. When run from inside Qt creator creates the PDF and emits the "image printed" message.
Otherwise does not create the PDF and emits the "some errors occurred" message.
Here is the tiny program:@ *** Pro file ****
#-------------------------------------------------Project created by QtCreator 2013-08-17T18:00:40
#-------------------------------------------------
QT += core gui printsupport widgets
TARGET = bugTest
TEMPLATE = app
SOURCES += main.cpp mainwindow.cpp
HEADERS += mainwindow.h
@@ *** main file ***
#include "mainwindow.h"
#include <QApplication>int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
@@ *** mainwindow.h ***
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <qpushbutton.h>class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void paintEvent(QPaintEvent *ev);private:
QPushButton *btn;
private slots:
void btnClicked();
};#endif // MAINWINDOW_H
@@ *** mainwindow.cpp *******
#include "mainwindow.h"
#include <QPainter>
#include <QPaintEvent>
#include <QPrinter>
#include <QMessageBox>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
btn = new QPushButton("doPdf", this);
move(0,0);
btn->adjustSize();
btn->move(100,15);
connect(btn,SIGNAL(clicked()),this,SLOT(btnClicked()));
}MainWindow::~MainWindow()
{
}
void MainWindow::btnClicked(){
bool ok;
QRect r=QRect(10,10,80,50);
QPrinter printer;
QPainter painter;
printer.setOutputFileName("print.pdf");
printer.setOutputFormat(QPrinter::PdfFormat);
ok=printer.isValid();
ok=painter.begin(&printer);
if(ok)
painter.drawRect(r);
if(ok)
QMessageBox::information(this,"","image printed on "print.pdf"");
else
QMessageBox::information(this,"","Some error occurred!");
}
void MainWindow::paintEvent(QPaintEvent * ev){
QRect r=QRect(10,10,80,50);
QPainter painter(this);
painter.drawRect(r);
}
@ -
Hi, when you launch your app from QtCreator (or from Terminal, cd:ing into bugTest.app/Contens/MacOs/) the print.pdf is created ok next to the .exe file.
But when you launch your app from Finder, the current directory is set somewhere else, my guess is where Finder's exe file is. And unless you run as root you'll get "Some error occurred".
So easiest way around this, change to an explicit path
*printer.setOutputFileName("/Users/Yourusername/Yourapp/print.pdf") or something similar. -
Wow!
this is fantastic solution (works!).Thanks a lot.