I am using Qt 4.7. I want to:
- fill text (a character, e.g.’A’) with an image
- and want that image to be scaled to the size of text (changes with change in font size)
- and want that the image be centered vertically and horizontally from the center of that text.

When this is achieved for one character, I want to do the same for many characters in a range (like: ‘a’-‘h’), or characters in a string entered at run-time.
For this currently I am employing this technique:
[ bgTextImage.h ]
QTextCursor cursor;
QTextCharFormat format;
QString imageFileName
[ bgTextImage.cpp ]
cursor = ui->textEdit->textCursor();
QPixmap pic(imageFileName);
QFontMetrics fontMetrics(format.font());
QSize fMSize = fontMetrics.size(0, "A", 0, 0);
QPixmap newPixmap = pic.scaled(fMSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
if(newPixmap.width() > fMSize.width())
{
int x = (newPixmap.width() - fMSize.width())/2;
newPixmap = newPixmap.copy(x, newPixmap.rect().y(), fMSize.width(), fMSize.height());
}
if(newPixmap.height() > fMSize.height())
{
int y = (newPixmap.height() - fMSize.height())/2;
newPixmap = newPixmap.copy(newPixmap.rect().x(), y, fMSize.width(), fMSize.height());
}
format.setForeground(QBrush(newPixmap));
format.setTextOutline(QPen(borderColor, ui->spinBoxWidth->value()));
ui->textEdit->clear();
cursor.insertText(text, format);
I am getting the results, but the image is not centered properly, as it should when aligned with CSS or other techniques.
I feel that this is a very amateur approach of getting this job done, and thus looking for a better or best-practice, if any. If not then, at least please suggest if there’s any way to improve the current process.
QPainter has the ability to do image composition (and you can use it outside the paint function). Seems like QPainter::CompositionMode_SourceOver with having the source image be the background, and then combining with your letter image would produce the result you want.
I hate just referring people to documentation, but the tutorial does have a really good example (ignore the openGL stuff unless you care).