Reputation: 19
I have to create some Images as placeholder for articles which have no own images / pictures. I already realized this in python, but i want to write the code in a qt app again. The python code is working and it looks like this:
def createImage(text="Leer", pfad="", bildname="TextBild.jpg", colorname='red'):
offset = 20 # weisses Textfeld um diesen Offset grösser darstellen
bild = Image.new('RGB', (width, height), colorname)
draw = ImageDraw.Draw(bild)
font = ImageFont.truetype("cour.ttf", 20)
w,h = draw.textsize(text, font)
draw.rectangle((((width-w-offset)/2,(height-h-offset)/2),((width+w+offset)/2,(height+h+offset)/2)), fill='white')
draw.text(((width-w)/2,(height-h)/2),text,'black',font)
## print "Erzeuge: " + pfad + os.sep + bildname, "\nPfad:\t"+pfad, "\nBildname:\t"+bildname
bild.save(pfad + os.sep + bildname) if os.path.exists(pfad) else bild.save(bildname)
But how to do this in Qt? I know there is QImage, QPainter, etc. but I dont't find a example what ist useful. Perhaps I do a system call to create a Image with text out of a qt app.
The image looks like this:
Thanks in advance for every useful hint.
Upvotes: 1
Views: 8659
Reputation: 19
Perfect! Thats excatly what I was looking for. Thank you very much!
bool createImage(QString text="Leer", QString path="./", QString imageName="TextImage.png", QColor aColor=Qt::red)
{
int width = 1024;
int height = 768;
int offset = 25;
int w = 400;
int h = 200;
QImage image(QSize(width,height),QImage::Format_RGB32);
QPainter painter(&image);
painter.setBrush(QBrush(aColor));
painter.fillRect(QRectF(0,0,width,height),Qt::darkGreen);
qDebug() << (width-w-offset)/2 << "\t" << (height-h-offset)/2 << "\t" << w << "\t" << h;
QRect aRect = QRect( (width-w)/2, (height-h)/2, w, h );
QRect aRectOffset = QRect( (width-w+offset)/2, (height-h+offset)/2, w-(offset/2), h-(offset/2) );
painter.fillRect(QRect(aRect),Qt::white);
painter.setPen(QPen(Qt::black));
painter.setFont(QFont( "Courier", 20) );
painter.drawText(QRect(aRectOffset),text);
QDir aDir = QDir(path);
if ( aDir.mkpath(path) )
return image.save(path + "/" + imageName);
else
return image.save(imageName);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
createImage("Ein einfacher Text\nDer auch mal länger sein kann.", "", "TestBild.png", Qt::green);
return a.exec();
}
I just played a little bit with your code above and now it is working for me really good. :-)
Upvotes: 0
Reputation: 383
For this particular image that you've given this will do the job:
QImage image(QSize(400,300),QImage::Format_RGB32);
QPainter painter(&image);
painter.setBrush(QBrush(Qt::green));
painter.fillRect(QRectF(0,0,400,300),Qt::green);
painter.fillRect(QRectF(100,100,200,100),Qt::white);
painter.setPen(QPen(Qt::black));
painter.drawText(QRect(100,100,200,100),"Text you want to draw...");
image.save("testImage.png");
Upvotes: 3