PDA

View Full Version : QText, how to only change font family?



UriTK
9th April 2019, 10:42
Hello. Sorry for the stupid question, but I've written up some code that I expected to only change font family, but it also changes the font size.



int id = QFontDatabase::addApplicationFont(font_path);
if(id != -1)
{
QStringList family = QFontDatabase::applicationFontFamilies(id);
ui_vp_message->setFont(family.at(0));
}


I have tried specifically using setFontFamily, but for some reason this does not change the font at all.
Am I approaching this the wrong way? Is there some other way I could change the font family?

anda_skoa
9th April 2019, 12:14
You are creating a new font object as setFont() takes on of these.

If you only want to modify one property of a font, you first retrieve the current font object, the modify the value you want to change and then set the modified object back on the widget.



QFont font = widget->font();
// modify font
widget->setFont(font);


Cheers,
_

UriTK
9th April 2019, 15:09
QFont font = widget->font();
// modify font
widget->setFont(font);


Thanks for the answer, it's a big ass leap in the right direction, but to verify if I'm majorly fucking up or not, this piece of code should then, in theory, only really change the font family, correct?



//add font to database
int id = QFontDatabase::addApplicationFont(font_path);
if(id != -1)
{
//get the font family name from said font
QStringList family = QFontDatabase::applicationFontFamilies(id);
//change currentfont's family to ^^^
currentfont.setFamily(family.at(0));
ui_vp_message->setFont(currentfont);
}


Maybe I'm not modifying it the right way but for some reason it keeps changing pointSize to the default value, instead of keeping the previous one.
As a sidenote, I do have QFont currentfont defined a bit above the code I showed.

anda_skoa
9th April 2019, 15:24
This is strange but maybe the new font doesn't have that particular size.

If the pointSize is the only thing that changes with the family you could "remember" it as well



currentfont = ui_vp_message->font();
const int pointSize = currentFont.pointSize();
currentFont.setFamily(...);
currentFont.setPointSize(pointSize);


Cheers,
_