QApplication setFont() and QTimer

188 Views Asked by At

When I setup font for Qt application, it has no effect on the part of code executed on QTimer's timeout() signal.

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QFontDatabase>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    int id = QFontDatabase::addApplicationFont(":/Blackbird.ttf");
    qDebug() << "Initial font:" << qApp->font();
    qApp->setFont(QFontDatabase::applicationFontFamilies(id).at(0));
    qDebug() << "Set font:" << qApp->font();

    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFontDatabase>
#include <QTime>
#include <QTimer>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QTimer *t = new QTimer(this);
    t->start(1000);
    connect(t, &QTimer::timeout, [=]{
        qDebug() << "Timer font:" << qApp->font();
        ui->label->setText(QTime::currentTime().toString());
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

Output of this code:

Initial font: QFont(Liberation Sans,11,-1,5,50,0,0,0,0,0)
Set font: QFont(Blackbird,12,-1,5,50,0,0,0,0,0)
Timer font: QFont(Liberation Sans,11,-1,5,50,0,0,0,0,0)
Timer font: QFont(Liberation Sans,11,-1,5,50,0,0,0,0,0)
...

But when I add some the code

    QTimer *t = new QTimer(this);
    t->setSingleShot(true);
    connect(t, &QTimer::timeout, [=]{
        qApp->setFont(QFontDatabase::applicationFontFamilies(0).at(0));
    });
    t->start(0);
    t->setSingleShot(false);
    t->start(1000);
    connect(t, &QTimer::timeout, [=]{
        qDebug() << "Timer font:" << qApp->font();
        ui->label->setText(QTime::currentTime().toString());
    });

everything works:

Initial font: QFont(Liberation Sans,11,-1,5,50,0,0,0,0,0)
Set font: QFont(Blackbird,12,-1,5,50,0,0,0,0,0)
Timer font: QFont(Blackbird,12,-1,5,50,0,0,0,0,0)
Timer font: QFont(Blackbird,12,-1,5,50,0,0,0,0,0)

It looks like the main thread and QTimer use different QCoreApplication::instance, but I checked qApp->applicationPid(), it is the same.
Is there a possibility to set the same font for all application at once?

UPD: I have just noticed, that the problem exists with Qt 5.14.1, which is currently default on Gentoo Linux.
With Qt 5.12.8, compiled from source with 'debug' option, it works properly.

0

There are 0 best solutions below