How to load multiple font of same familiy - c++

I am writing an application using the Qt framework. In the display, I have to show multiple information, but using different types of font of the same family, Montserrat.
What I have done so far to load the fonts is:
int ultralightid = QFontDatabase::addApplicationFont(":/Montserrat_UltraLight.tff");
QString UltraFont= QFontDatabase::applicationFontFamilies(ultralightid ).at(0);
QFont font1(UltraFont,QFont::Normal);
font1.setPixelSize(50);
int lightid = QFontDatabase::addApplicationFont(":/Montserrat_Light.tff");
QString LightFont= QFontDatabase::applicationFontFamilies(lightid).at(0);
QFont font2(LightFont,QFont::Normal);
font2.setPixelSize(150);
label1->setFont(font1);
label2->setFont(font2);
label1->setText("bla bla");
label2->setText("bla bla");
The font sizes are correct, but the font itself it is not. From what I have noticed (trying with Hairline_Montserrat,Light_Montserrat,UltraLight_Montserrat), it is as if the fonts have a sort of priority. If I declare them all, all the fonts are the Light one, if I comment that font type, all of them are Hairline one, otherwise (last priority) the labels use the ultralight font.
I have tried adding other font type (from other families) and in that case my code works correctly.
If I use
qDebug()<<QFontDatabase::applicationFontFamilies(ultralightid);
qDebug()<<QFontDatabase::applicationFontFamilies(lightid);
both of them print the family "Montserrat".
I use the qrc file and the AUTORCC flag in the CMAKE (it should be similar using qmake) and all the file are uploaded correctly.
Do you know if there is another way to add fonts of the same family? Or is there something I am doing wrong?
Here are the fonts:
https://www.onlinewebfonts.com/download/9d31c906a6cc6064bbe7d33d51058317 light
https://it.allfont.net/download/montserrat-light/ ultralight

This is an old question but I was just struggling with exactly the same problem when trying to load normal, bold, ... versions of a font family in Qt.
I solved the problem (although in a somewhat hacky way) by simply giving each of the ttf files a different family name. I used Typograf, simply open the font, right click to open properties and then click rename. There are probably many other tools that do this too.

You don't need to manage font files from one family separatelly.
I suggest this solution:
Create a folder with all ttf's of the same family.
Load all files from the folder via id = QFontDatabase.addApplicationFont(path)
Collect all font families from these files via QFontDatabase.applicationFontFamilies(id)
Check if only one and desired family is loaded, and the family name is exactly the same as requested, or warn the user about these errors.
Create font object font = QFont(family)
Then for example, font.setItalic(True). If Italic version of family is loaded, it will be used, otherwise it will be created from Regular by QT.

Related

wxWidgets include image during compile time

I've been trying to make a simple wxWidgets program with just a button with a picture on it. I've been able to make the button with the image on it easily enough, but my problem arises when including it.
So far, I've only been able to fetch the image during run-time (the image has to be in the same folder as the .exe file; otherwise, I get error 2: the system cannot find the file specified). With this method, I have no problems -- the program works just fine. What I'm trying to do, however, is to #include the file so that it is embedded during compile-time, so that it doesn't need to be available during run-time.
I've tried #including the file (both as .png and as .xpm), and I've also tried adding it to the resource includes (this is on Visual Studio 2017). Neither of these worked -- the first method still required the image to be in the same folder, and the second failed during compilation (as far as I can tell, it wasn't able to read the .xpm file).
Here is the relevant code, if it helps:
/*relevant includes*/
#include "happyFace.png" //this isn't working. the file is still needed
||
#include "happyFace.xpm" //ditto
/*I have also tried putting these lines in the resource includes.*/
/*code*/
wxInitAllImageHandlers();
wxBitmap bitmap("happyFace.xpm", wxBITMAP_TYPE_XPM); //only works in same directory at run-time
||
wxBitmap bitmap("happyFace.png", wxBITMAP_TYPE_PNG); //ditto
wxButton *button = new wxButton(this, ID_BMP_BUTTON);
button->SetBitmap(bitmap);
//the rest of the button programming and stuff
Sorry if I haven't provided enough information; I can provide more if necessary. I would really appreciate any help. Thanks!
Two possibilities... Number 1 is simplest. It's been a long time since I wrote the code I'm looking at, so the details are fuzzy.
In Visual Studio, Solution Explorer, add the image into the resource files. Assume the name of the resourse is sample.rc. Then it can be used like so to set the main icon...
SetIcon(wxICON(sample));
Method 1 must be used in order for MS Windows Explorer to display the main icon. I do not remember how to use .rc resources for other things, but it should be easy to figure out.
I did it this way before I discovered VS resource (.rc) files. Compile the file-image into the program "by hand." In other words, write a program that will read an image file and produce bit-for-bit copy in a .cpp file. Then compile that .cpp into the program. Here I have the file-image in memory as an object named dj::main_cursor. Note that the in-memory version is a bit-for-bit copy of a .cur file.
dj::captured_file &c1file(dj::main_cursor);
wxMemoryInputStream cistr(c1file.contents, c1file.size);
cursor1 = wxCursor(wxImage(cistr, wxBITMAP_TYPE_CUR));
FYI, I defined the structure dj::captured_file like so:
struct captured_file {
const char *name;
const unsigned long size;
const void *contents;
captured_file(const char*fn, size_t sz, const void*c)
: name(fn)
, contents(c)
, size(sz)
{}
};
See also, Embedding PNG Images into Windows RC Files
I found some other documentation.
Resources and Application Icon All applications using wxMSW should
have a Windows resource file (.rc extension) and this file should
include include/wx/msw/wx.rc file which defines resources used by
wxWidgets itself.
Among other things, wx.rc defines some standard icons, all of which
have names starting with the "wx" prefix. This normally ensures that
any icons defined in the application's own resource file come before
them in alphabetical order which is important because Explorer
(Windows shell) selects the first icon in alphabetical order to use as
the application icon which is displayed when viewing its file in the
file manager. So if all the icons defined in your application start
with "x", "y" or "z", they won't be used by Explorer. To avoid this,
ensure that the icon which is meant to be used as the main application
icon has a name preceding "wxICON" in alphabetical order.
http://docs.wxwidgets.org/3.1.0/page_port.html
Here is how you should do it:
#include "happyFace.xpm"
wxBitmap bitmap = wxBitmap( happyFace ); // assuming the variable name is "happyFace" inside the xpm
Then you will use bitmap object just like usual. Assuming that the file happyFace.xpm is available for compilation.

How does Qt select a default style?

In a Qt GUI application, QApplication::style()->objectName() will return the current style, for example "windowsvista".
How/where does it choose this default style, and what information does it use to decide?
Qt comes with builtin styles, these are (on my 5.9.2):
Windows
WindowsXP
WindowsVista
Android
Fusion
Macintosh
each one having its own class, derived from QStyle.
To see which ones are available (it depends on Qt build configuration):
const auto & styles = QStyleFactory::keys();
for(const auto & s : styles)
{
qDebug() << s;
}
Custom plugins (i.e. libraries in the QTDIR/plugins/styles directory) would be shown as well, if present.
How the default style is chosen?
Default style is searched in QApplication method style(), in qapplication.cpp file, in this order:
The style override, if set by the environment variable QT_STYLE_OVERRIDE (this is set in QApplicationPrivate::process_cmdline());
The style returned by QApplicationPrivate::desktopStyleKey() (this method loads a list of styles from the current platform theme and select the first name from this list that is present in the QStyleFactory::keys() list);
The first item in QStyleFactory::keys() list.
If a style could not be determined, the function will assert
Q_ASSERT(!"No styles available!");
In the documentation:
Qt contains a set of QStyle subclasses that emulate the styles of the
different platforms supported by Qt (QWindowsStyle, QMacStyle etc.).
You can set the style by using a key: windowsvista for example, fusion, macintosh, etc. When using any key, the style returned will be a subclass of QStyle. Depending on the platform you're using, you will have access to a certain number of keys.
How/where does it choose this default style
It is done in the QStyleFactory source file. You can also take a look a the QStyle source file to get a hang of what's going on.
what information does it use to decide
The default style is platform dependent, and then you can choose any style among the keys at your disposition on this platform.

QT QIcon properties for custom widget in designer

I have been working for a little while now on creating a QT custom designer widget for GUI menus. The idea being that you simply drag it into the designer, select the number of frames you'd like, how many buttons per frame, etc. and it generates and sizes everything for you.
The way the widget is structured there are properties to configure each button for the frame you are in. For example, you would use the button0Text field to enter text under Button0 while editing in frame 0, then use it again to edit Button0 which is in frame 1. Both buttons would retain the individual changes for each frame.
The Problem
Normally when I switch frames all of my properties are updated to reflect the status of the frame. The exception being QIcon. The correct icon is retained in the actual graphical representation and builds correctly, however the file path in the property list is always of the last edited for that property. I think this will be extremely confusing to an end user and I have found no way to fix it. So for example, if I set text and icons in frame 0 then switch to frame 1 the text in the property list will update to reflect the state of frame 1 but the icon path names will still show my last edit in frame 0 and not the actual icon in frame 1.
I have tried things as simple as:
setProperty("button0Icon", getButton0Icon());
That code works on properties like text, but not for the icon. I try executing it immediately after changing frames.
I have also tried:
#ifndef Q_WS_QWS
QDesignerFormWindowInterface *form = QDesignerFormWindowInterface::findFormWindow(this);
if(form){
QDesignerFormEditorInterface *editor = form->core();
QExtensionManager *manager = editor->extensionManager();
QDesignerPropertySheetExtension *sheet;
sheet = qt_extension<QDesignerPropertySheetExtension*>(manager, this);
int propertyIndex = sheet->indexOf("button0Icon");
sheet->setChanged(propertyIndex, true);
sheet->setProperty(propertyIndex, getButton0Icon());
}
#endif
And:
int propertyIndex = this->metaObject()->indexOfProperty("button0Icon");
QMetaProperty property = this->metaObject()->property(propertyIndex);
property.write(this, QIcon());
Nothing seems to update the property list in the designer.
I have all properties, including all QIcon properties properly declared in the header file with Q_PROPERTY and assigned getter and setter functions.
To be clear, the icon values are indeed retained through each frame when compiled. So it is functioning, just unclear for most users.
If anyone has any experience with this or any ideas please let me know. Thanks.
I have discovered that QIcon does not store file names/paths. The file names are only used for the creation of the QIcon. I think this is most likely the reason I do not get any feedback in the Property Browser for my QIcon properties.
Instead I have chosen to hide this property in the designer and add three new ones. Three QUrl properties, each of which is used to supply an image file. I use three because I want to construct a QIcon that contains Modes/States for normal, disabled, and pressed operations.
I take each of these QUrls and save them in QStringLists behind the scenes so their values are stored. I then construct my QIcon using the file names provided from the QUrls.
I would much prefer to be using the native QIcon in the designer for this, any thoughts or feedback are appreciated.

How can i add custom fonts in cocos2d-x

To add custom fonts in cocos2d-x i followed the following steps.
Download a font.
paste it in resource file of my project without any subfolder.
Add my font in info.plist in Fonts provided by application as Roboto-thin.ttf
Add it in Copy bundle resources.
I used the following code to display the font:
CCLabelTTF* cycleLabel1 = CCLabelTTF::create(" ", "Roboto-Thin.ttf", 80);
I tried with removing the extension also in the code, but no use. Anyone please help me to solve this problem.
On IOS, inside your CCLabelTTF::create() you have to use the NAME of the font, not the file of the font. In your case it is probably "Roboto Thin". Something like this:
CCLabelTTF* cycleLabel1 = CCLabelTTF::create(" ", "Roboto Thin", 80);
You can see font names installing them and opening them in Font Book (assuming you use mac)
Note on Android you still call fonts using its file name.
It is very explained (not very well at all) in the documentation.
http://www.cocos2d-x.org/wiki/How_to_Use_Custom_TTF_Font_on_iOS
Try this:
AddFontResource(L"xxx/yyy/Roboto-Thin.ttf");
before CCLabelTTF::create(" ", "Roboto-Thin", 80);
and then RemoveFontResource(L"xxx/yyy/Roboto-Thin.ttf");
Make sure that the name of the font and the file name are the same

linux, C++, xft : how to use it?

I try to use Xft, the tutorial, well let them calling that a tutorial... looks like it was written in a north korean camp... I also found this one. So let me try to do a step-by-step :
// g++ XftTest.cc -lX11 -lXft `pkg-config --cflags freetype2`
#include<unistd.h>
#include<X11/Xlib.h>
#include<X11/Xutil.h>
#include<X11/Xft/Xft.h>
int main()
{
Display *display;
XftFont *font;
XftDraw *xftdraw;
XRenderColor xrcolor;
XftColor xftcolor;
display = XOpenDisplay(0);
Window XP = XCreateSimpleWindow(display,DefaultRootWindow(display),0,0,360,90,0,0,0);
XMapWindow(display,XP);
font = NULL; /* added 6/16 */
//font = XftFontOpenName(display,0,"NorthKorea-50"); // how to check if this is good ?
font = XftFontOpenName(display,0,"") /* added 6/16 */
if (!font) return 1;
xftdraw = XftDrawCreate(display,XP,DefaultVisual(display,0),DefaultColormap(display,0));
xrcolor.red =65535;
xrcolor.green=0;
xrcolor.blue =0;
xrcolor.alpha=65535;
XftColorAllocValue(display,DefaultVisual(display,0),DefaultColormap(display,0),&xrcolor,&xftcolor);
XftDrawString8(xftdraw, &xftcolor, font, 20,70 , (XftChar8 *)"Joe Dalton", 10);
XFlush(display);
sleep(2);
XftDrawDestroy(xftdraw);
XftColorFree(display,DefaultVisual(display,0),DefaultColormap(display,0),&xftcolor);
return 0;
}
as you can see, in the XftFontOpenName :
XftFontOpenName(display,0,"NorthKorea-50")
if you write a bullshit, like I did, there is no error or something to tell me that I don't have a font called NorthKorea. That make sense since XftFontOpenName returns the nearest font from the string.
So, how can I check if my font match or not ? how can I use a font like arial? I tried XftFontOpenName(display,0,"arial-50"), I got nothing different.
On my system, I have these folders in my fonts folder :
$ls /usr/share/fonts/
100dpi 75dpi cyrillic encodings misc OTF TTF Type1 util
can I use any font in these folders by the same way ?
if you guys have some nice internet links, it would be a pleasure for me to take a look.
n.b. : there is no xft tag...
update 6/16
I'm still stuck with dat stuff...
I don't understand, if I replace
font = XftFontOpenName(display,0,"NorthKorea-50");
by
font = XftFontOpenName(display,0,"");
it still loading a font...
xlsfonts return a lot of stuff, like dat one :
-monotype-courier new-bold-r-normal--0-0-0-0-m-0-iso8859-10
but passing this as argument to XftFontOpenName changes nothing; I try to load a font with XftFontOpenXlfd too, it returns always NULL...
xft uses fontconfig for font discovery. xlsfonts is a way to query the old X core fonts system fontconfig replaced. xlsfonts results won't map in any reliable way way to the fontconfig state.
So:
forget about any shortcut where xft work sort-of like the X core font system documented in last centuries tech books. It is completely different. It is not X core fonts with antialiasing and truetype support. It is something that can use modern fonts and do antialiasing, but definitely not X core fonts in any form
Read the fontconfig documentation, the fontconfig configuration files on your system, and use fontconfig utilities (fc-query, fc-list, etc) to query the fontconfig state
as the people who maintain xorg (both x core fonts and fontconfig) already told you, do not try to use xft directly. xft is the product of the first attempt to write a new font stack. Its capabilities are not sufficient to manage modern text and modern fonts. The part dealing with modern font format complexities has been spun out in pango a long time ago (because it was proving complex enough it deserved a separate project). If you try to use xft alone, you'll hit the deficiencies in pre-pango code sooner or later, and no one will be interested in fixing your problems because the same code has already been subjected to a decade of fixes pango-side. Avoiding pango is not a shortcut. Avoiding pango is trying to rely of an half-finished, abandonned for years project.
forget about matching a specific font file. fontconfig will actively fight any attempt to work this way. In the post-core-fonts world, you give the font system a font pattern, and it will build a matching font for you. If the result is not the font file you expected that's because the file was evaluated and found lacking. If you want fontconfig to use this file you will have to fix the font file (add the missing glyphs, the missing font styles, etc), not write code to try to force it anyway. Fontconfig considers that it's more important to render a text your users can read, than to only render the parts your pet font can do. And yes that's now how you're used to think about it on other systems. fontconfig is different. Nothing short of a rewrite will make it behave like you expect. No one is interested in this rewrite because by and large fontconfig has been quite successful those past years.
fonts opentype text-rendering fontconfig linux
You should not pass an empty string to XftFontOpenName and expect to match a font. Xft provides support for core fonts and the structure nested within XftFont is a union of XFontStruct and XftFontStruct. X11 fills in the default font in the XFontStruct when creating new instances, so in the case of empty string you are likely getting the default core font.
In the simplest approach, one can hard code a font name like this:
const char *font_name = "Arial-20";
XftFont *font = XftFontOpenName (display, DefaultScreen(display), font_name);
Or you could use XftFontMatch and check the "results" before passing the pattern to XftFontOpenPattern. See http://keithp.com/~keithp/talks/xtc2001/paper/xft.html#sec-editing
Note that XCloseDisplay is missing.