Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QPrinter doesn't print with colors.



  • Hello, I'm currently making a notepad in Qt and I tried to print a file with colors.
    836ac905-e696-4b95-8d6a-ad8fa1b43757-image.png
    this is the file, sorry it's in italian.

    This is my code:

    void MainWindow::on_print_clicked()
    {
        //Getting the settings.json file
        QFile settings(QCoreApplication::applicationDirPath() + "/settings.json");
        QByteArray content;
        if(settings.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            content = settings.readAll();
            settings.close();
        }
    
        QJsonParseError *errPars{new QJsonParseError()};
        QJsonDocument jsonDoc{QJsonDocument::fromJson(content, errPars)};
        QJsonObject obj{jsonDoc.object()};
    
        //Setting up the printer
        QPrinter printer;
        printer.setResolution(QPrinter::HighResolution);
        printer.setPageSize(QPageSize::A4);
        if(obj["printHorizontally"].toBool() == false)
            printer.setPageOrientation(QPageLayout::Portrait);
        else
            printer.setPageOrientation(QPageLayout::Landscape);
        if(obj["printWithColors"].toBool() == false)
            printer.setColorMode(QPrinter::GrayScale);
        else
            printer.setColorMode(QPrinter::Color);
        //Creating the page setup dialog
        QPageSetupDialog *pageSetup = new QPageSetupDialog(&printer, this);
        //Creating the printpreview dialog
        QPrintPreviewDialog *printPrev = new QPrintPreviewDialog(&printer);
        //QObject::connecting printPrev paint signal to print slot
        QObject::connect(printPrev, &QPrintPreviewDialog::paintRequested, this, &MainWindow::print);
        if(pageSetup->exec() == QDialog::Accepted)
        {
            printPrev->exec();
        }
    }
    
    //Print slot
    void MainWindow::print(QPrinter *p)
    {
        TextEdit *edit{getTabTextEdit()};
        edit->print(p);
    }
    

    So it checks if in the settings.json file the "printWithColors" is true, and it is.
    987a8531-b781-4667-a6b4-d7285f234a00-image.png
    Even if I've written printer.setColorMode(QPrinter::Color);, it still doesn't print in colors.
    I tried and everything is correct but it is all black.
    How can I solve this?



  • @HenkCoder I would assume that content of your editor is being treated as plain text?



  • @artwaw I don't know, how do I make to save formatting infos?



  • @HenkCoder Try simple check. I assume that by TextEdit *edit{getTabTextEdit()}; you get the QTextEdit instance from the Ui, right? So I'd check acceptRichText() and the flags from autoFormatting().
    Also doing qDebug() << edit->toHtml(); will show you if formatting tags are present.
    On logic if you see rich text in the Ui it should also get printed, unless you mismatched printer settings or something.


Log in to reply