Get QPixmap dynamic image path from std::string - c++

I have a problem with the QPixmap under Qt. I want to set the Pixmap Image Path dynamically from a std::string. I have tried some variations, but without success.
This is my code:
QPixmap pixmap("data/25eaad8879f1d018caec98546279804f.png"); // this is working
// label
ui->imageSite1->setPixmap(pixmap); //working
But if I try to set the pixmappath dynamically, I don't see the image (inside the label).
e.g.
string path = "data/"+imgname+".png"; // imgname is a dynamic parameter
QPixmap pixmap(path); // this is not working
// label
ui->imageSite1->setPixmap(pixmap);
How can I do this correctly?

If you take a look at the Documentation of QPixmap, you'll see the load method declared as taking a QString as parameter. So you either have to build a QString directly (judging by your example, I think this is the better way) or convert the std::string to a QString with a constructor of the latter.

I have to load the filepath from a textfile and at the end of the line was a \n. They can't load the image in this case.
I removed this and load the pixmap via the load method. Now it's working.
string path = "data/"+imgfilepath;
QString testPath = QString::fromStdString(path);
qDebug() << testPath;
QPixmap pixmap;
pixmap.load(testPath);

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);");

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

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?

How to save a QPixmap as a picture in a folder with C++ and Qt?

I'm trying to code a C++ function to save a selected picture to my program directory, using a Qt GUI.
So far, the "save" function I'm using on my QPixmap object won't save anything, and I can't figure out why.
Here is the code :
qImage = new QPixmap(path);
QPixmap qImage2 = qImage->scaled(this->width(),this->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
qImage2.toImage();
qImage2.save(QDir::currentPath());
qDebug()<<QDir::currentPath();
Can anyone help me ? :)
QDir::currentPath() returns the current working directory. Obviously, the filename itself is not specified. Simply append the needed filename, for example: QDir::currentPath() + "/123.png"
QPixmap::toImage() is a const method returning a QImage converted from a QPixmap. It literally does nothing useful in your code, remove it or use QImage instead.
QDir::currentPath() returns the current working directory which is not necessarily an application executable directory. Use QCoreApplication::applicationDirPath() instead if you need an executable directory.
Also, as pointed out by Violet Giraffe, there could be write permission issues.

QFileInfo::absoluteFilePath() not working?

I am using Qt 4.7.4. I have a relative file path that I am storing as a QString and I want to later convert it into an absolute file path. However, when I create a QFileInfo object from that QString and call absoluteFilePath(), the path is still not absolute. For example:
QString fn = "..\..\..\..\..\..\App\exampledata\doll\everything-F.wrl";
QFileInfo fi(fn);
QString fn2 = fi.absoluteFilePath();
And now fn2 contains "C:/../../../App/exampledata/doll/everything-F.wrl", while I want it to contain "C:/App/exampledata/doll/everything-F.wrl". I could manually remove the useless dots, but that's tedious.
That's not the function you should be calling if you want a canonical path. You should be using QFileInfo::canonicalFilePath instead.

QImage file path

I don't see this in the documentation anywhere, so it probably doesn't exist, but just in case:
I have a function that accepts as a parameter a vector of QImages. Each QImage was loaded from disk at some point and has not been edited--it is just read from. Ideally what I'd like to do is loop over all the QImages and output a list of their file paths to an XML file.
Unfortunately, I'm not seeing in the documentation any way to get at the original file path that the image was loaded from. So my question is, is it possible, given only a QImage, to figure out what file path the QImage was originally loaded from or not?
Something along the lines of:
QString QImage::getOriginalFilepath();
I know this is probably a futile question, but its always worth a shot to ask, I suppose.
(I'm using Qt 4.7, by the way.)
I looked through the code, and that information doesn't appear to be saved anywhere. QImage::load (and the constructor) uses QImageReader(fileName,format).read() and then copies the result to itself. The QImageReader is set to delete the device representation (the opened file object) as soon as it's finished reading.
So, in summary, it appears that this is not possible.
Also for me it seems that QImage doesn't provide an interface to get its path. I also think that this is not a missing feature, because there's no need to tie a QImage to a specific path. In the majority of all use cases the QImage has no corresponding physical file.
So the best way in your situation would be to subclass QImage and add this feature:
class MyImage : public QImage {
QString path_;
public:
MyImage(const QString& path);
QString path(); // getter
};
I omit the implementation details.
I usually create a struct for hold the QImage and the image path.
struct Image
{
QImage imageData;
QString filename;
};