writing images to .odf/.odt with QtTextDocumentWriter giving realy low quality output - c++

I'm handling some charts in my Qt application and need to output them to a .odf/.odt file. Found on Qt documentation about this method.
I've implemented it by getting a QPixmap from the chart and then converting it to a Qimage that is written to the QTextDocument.
When i open the output document my charts are realy blurry, seems like a bad compression or something is happening.
What did i get wrong about handling .odf?
If i try to use the same QTextDocument to write to a .pdf or in a QTextEdit seems to work fine. But realy need to get the final output to a .odf file so that's no good for me. Actualy also a docx or similar could be fine
//create a chart and return it as an image
QImage getChartImage(foo) {
//stuff that handles creating a (QChart *chart) from given foo data
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
chartView->resize(1000,750);
QPixmap chartImage = chartView->grab();
chartImage.save("test.png", "PNG"); //just for testing, here looks fine
return chartImage.toImage();
}
and then in my main
//in main
Qimage chartImage = getChartImage(foo);
//setting up document
QTextEdit *editor = new QTextEdit; //not needed, but this works too
// if no editor should be:
//QTextDocument *document = new QTextDocument;
QTextDocument *document = new QTextDocument(editor);
QTextCursor cursor(document);
//adding image to document
document->addResource(QTextDocument::ImageResource, QUrl("my_img.png"), chartImage);
QTextImageFormat imageFormat;
imageFormat.setName("img1.png");
cursor.insertImage(imageFormat);
cursor.insertBlock();
cursor.insertText("some random text!");
//show on editor; not needed but works
editor->setDocument(document);
editor->setWindowTitle(QObject::tr("I should work fine!"));
editor->resize(1000, 750);
editor->show();
//and here the bad output happens
QString fileName = QFileDialog::getSaveFileName(nullptr,QObject::tr("Save File"),"output_file.odf",QObject::tr("Open Document ('''.odf)"));
QTextDocumentWriter fileWriter (fileName);
fileWriter.setFormat("odf");
fileWriter.write(document);
Here you can see how the charts get's saved to the document and how it should actualy look like.
blurry output on .odf
output on QTextEdit
saving the QPixmap as .png
Any idea on how to fix this? Or maybe an other method that I can use?

Related

Qt stylesheet to use an image from memory

Qt stylesheets allow customizing of icons, for example the drop-down icon in a combo box. But all examples and docs which I have yet seen require having the image stored in a url. Then you can write for example QComboBox::down-arrow { image: url(path-to-file.png); }.
My question is: isn't there any trick which would allow to work around the fact that the file must be stored somewhere and use for example a pixmap from the memory?
I am asking because recently I found a nice hack which allows using QPixmap data to be used when displaying images in widgets which otherwise accept richtext (HTML formatted). See this code:
QPixmap preview;
// ... generate the pixmap here
QByteArray data;
QBuffer buffer(&data);
preview.save(&buffer, "PNG");
QString img = QStringLiteral("<img src='data:image/png;base64, %1'/>").arg(QString::fromLatin1(data.toBase64()));
//... and now you can display the image anywhere Qt accepts HTML formatted text,
// e.g. in QToolTip (which is my usecase).
This way I can use data from memory without saving it to file.
I am curious if there isn't any similar trick for images used in Qt style sheets.
There's nothing special, just put path to your image:
setStyleSheet("background-image: url(/path/to/file.png);");

Displaying picture that is not in resources of Qt

I am currently writing an application in Qt, which is basically a warehouse. An application reads CSV, enables user to process it and enables to show picture of each good. I tried displaying picture using QLabel and Pixmap, however nothing happens even though the file is in the same folder and the name provided is exactly as it should be. Is it the resources issue or my code fails somehow? Is there any possibility to display the image without adding it to resources in order to avoid adding many photos manually?
void ImageViewer::viewImage(QString imgName)
{
QString pathWithName = imgName;
pathWithName.append(".jpg");
ui->label->setPixmap( QPixmap(pathWithName) );
ui->label->show();
update();
}
Sorry for any mistakes in post creation or code displaying here- it's my first post.
Edit:
I am adding code from MainWindow (called CsvReader in my project) to how I'm invoking the method viewImage:
void CsvReader::on_imgView_clicked()
{
ImageViewer* img = new ImageViewer(this);
img->setModal(true);
img->exec();
QModelIndex List selInd ui->tableView->selectionModel()->selectedIndexes();
QString id = model->item(selInd.first().row(), 0)->text();
img->viewImage(id);
}
Edit 2:
Solved. Had to change path using QDir:
QDir* directory = new QDir("/home/kokos/Magazyn/photos");
QFileInfo checkFile(*directory, pathWithName);
Thanks in advance,
Kokos
Confirm your file's location and existence first. Add this;
QFileInfo checkFile(pathWithName);
if (checkFile.exists() && checkFile.isFile()) {
// your code
}

How to create or modify a QT form (after compilation) based on a text file

I would like to create a windows application that displays a window based on a existing text file. For example, I may have a text file with the following information:
window_size 400, 300
push_button 2
radio_button 5
My program should be able to read this text file and create a window of 400 x 300 pixels, with 2 push buttons and 5 radio buttons. Of course, the content of the text file may change and is unpredictable. Please ignore at this moment other nessesary data, like the position and size of the buttons, I just need to know if its possible to do this, and a general idea on how to do it.
I'm using Qt with C++. I may change Qt if there is a better option to do this, but I must stick with C++.
You should parse and set accordingly.
Create a QWidget, parse the first line of the text file, set its size. Then parse next lines to get the number of buttons, create widgets dynamically. Something like:
// main
// ...
QString geoLine = stream.readLine();
int width = geoLine.split(" ")[1].toInt();
int height = geoLine.split(" ")[2].toInt();
QWidget * widget = new QWidget();
widget->setGeometry(0, 0, width, height);
// create a layout for the child widgets, then create and add them dynamically.
QVBoxLayout * layout = new QVBoxLayout();
int nButtons = stream.readLine().split(" ")[1];
// full control of dynamically created objects
QList<QPushButton *> buttons;
while(nButtons > 0) {
QPushButton * button = new QPushButton();
buttons.append(button);
layout.addWidget(button);
nButtons--;
}
// same for radio buttons
// ...
widget->setLayout(layout);
widget->show();
// ... etc, app exec,
qDeleteAll(buttons);
delete widget;
return 0;
If you want to learn the widget type from push_button or radio_button directives; you must switch - case onto those parsed strings.
There is also completely another way. You can create a form (.ui) file using an XML data. You must create a ui class (like the template designer form class created by Qt), and create its .ui file according to your text file - parsed and converted to a proper XML.
As far as I know Qt handles the widget creations using that XML information, and generates the file ui_YourClass.h..
As canberk said you can use native Qt UI file format .ui by usage of QUiLoader class - see reference http://doc-snapshot.qt-project.org/qt5-5.4/quiloader.html

Print a textEdit in Qt

How can I print the text available in a textEdit using Qt creator (C++)? Please help me with this. I created a note pad using a textEdit. Now I want to print the note pad content. That mean the text typed in textEdit. So please help me.
please mention header files that I need to include as well.
Here is something I tried previous. but it's not working. so please help me with this.
void MainWindow::on_action_Print_triggered()
{
QString textFromField = ui->txtEdit->toPlainText();
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFileName("print.ps");
QPainter painter;
painter.begin(&printer);
printer.newPage();
painter.end();
}
QTextEdit already has method which allows you print it's content, so you don't need QPainter. Use this (I printed pdf as example):
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("outputt.pdf");
ui->textEdit->print(&printer);
print()
And of course you need
#include <QPrinter>
but I think that it is already added in your project.

Qt Background Image for a QPushButton

I need to put an image from the internal resources as a background image of a QPushButton. I need also to adapt the size of the image to the size of the button.
I have found here some way to do that, but nothing seems to work.
In the last reply it was suggested the use of the following code:
QPixmap pixmap("image.jpg");
QPalette palette;
QPushButton *button= new QPushButton(this);
palette.setBrush(button->backgroundRole(), QBrush(pixmap));
button->setFlat(true);
button->setAutoFillBackground(true);
button->setPalette(palette);
So I took that code and changed it a bit 'cause I'm using a ui made with QTCreator:
void MyDialog::SetBgImage(QWidget *pButton)
{
QPixmap pixmap(":/Icons/images/Sfondo.png");
QPalette palette = pButton->palette();
palette.setBrush(pButton->backgroundRole(), QBrush(pixmap)); // 1
QPushButton *pPButton = qobject_cast<QPushButton *>(pButton);
if (pPButton!=NULL)
pPButton->setFlat(true);
pButton->setAutoFillBackground(true);
pButton->setPalette(palette); // 2
}
In the constructor I call it in this way:
SetBgImage(ui->pushButton_Button1);
when the dialog is showed the button is displayed correctly. Unfortunately when I close the dialog I get the following error message:
* glibc detected * ./MyAppName: malloc(): memory corruption: 0x0047dc78 ***
If I remove the line marked with //1 or the line marked with //2 the error disappear.
Any ideas?
button->setStyleSheet("border-image:url(:/Icons/images/Sfondo.png);");
Or change stylesheet from designer.
ui->pushButton_5->setStyleSheet("backgroundimage:url(/home/Desktop/qtproject/
sample2/images
/11.png);");
For Setting background in Qpushbutton
You can use this code, it worked for me :
ui->pushButton_2->setStyleSheet("background-image:url(C://Users//XXXX//Desktop//menu//icon.png);");