Search code examples
qtqpainterqprinter

QPainter::begin(): Returned false


So i'm using QT 5.15.2 and what i'm trying to do here is print ot PDF the content of a QTableView into a PDF File here's my code

 void ManageTeachers::on_print_clicked() {

    QPdfWriter pdf("C:");
    QPainter painter(&pdf);

        int i = 4000;
            painter.setPen(Qt::blue);
            painter.setFont(QFont("Arial", 30));
            painter.drawText(1100,1200,"List of teachers");
            painter.setPen(Qt::black);
            painter.setFont(QFont("Arial", 15));
           
            painter.drawRect(100,100,7300,2600);
            painter.drawRect(0,3000,9600,500);
            painter.setFont(QFont("Arial", 9));
            painter.drawText(200,3300,"CIN");
            painter.drawText(1300,3300,"First name");
            painter.drawText(2100,3300,"last name");
            painter.drawText(3200,3300,"phone");
            painter.drawText(5300,3300,"email");

            painter.drawText(5300,3300,"salary");
            QSqlQuery query;
            query.prepare("select * from teacher");
            query.exec();
            while (query.next())
            {
                painter.drawText(200,i,query.value(0).toString());
                painter.drawText(1300,i,query.value(1).toString());
                painter.drawText(2200,i,query.value(2).toString());
                painter.drawText(3200,i,query.value(3).toString());
                painter.drawText(4500,i,query.value(4).toString());
               i = i + 500;
            }
            int reponse = QMessageBox::question(this, "Génerer PDF", "<PDF Enregistré>...Vous Voulez Affichez Le PDF ?", QMessageBox::Yes |  QMessageBox::No);
                if (reponse == QMessageBox::Yes)
                {

                    painter.end();
                }
                if (reponse == QMessageBox::No)
                {
                     painter.end();
                } }

The problem is that in the console i get these errors

QPainter::begin(): Returned false
QPainter::setPen: Painter not active
QPainter::setFont: Painter not active
QPainter::setPen: Painter not active
QPainter::setFont: Painter not active
QPainter::drawRects: Painter not active
QPainter::drawRects: Painter not active
QPainter::setFont: Painter not active
QPainter::end: Painter not active, aborted

Any help ? i added the QT+= printsupport multimedia


Solution

  • QPdfWriter pdf("C:");
    QPainter painter(&pdf);
    

    This is very suspect. If you consult the documentation for QPdfWriter it notes that the first parameter should be a filename. "C:" is not a filename. You need to pass the name of the file you want to write to, something like:

    QString filename("C:/my_file.pdf");
    QPdfWriter pdf(filename);
    QPainter painter(&pdf);