如何在 Qt 应用程序中使用 windows 字体

How to use a windows font in Qt application

我注意到 Qt 在 windows 7 上使用的默认字体与系统字体略有不同。

在本例中字母 'o' 上清晰可见:

 

这是我的代码:

int main(int argc, char *argv[])
{
  QApplication app(argc, argv);
  QMainWindow mainWin;

  QWidget* central = new QWidget(&mainWin);
  central->setLayout(new QHBoxLayout);

  QPushButton* ba = new QPushButton("Tool A", central);
  central->layout()->addWidget(ba);

  QPushButton* bb = new QPushButton("Tool B", central);
  central->layout()->addWidget(bb);

  mainWin.setCentralWidget(central);
  mainWin.setWindowTitle("Tools");
  mainWin.show();
  return app.exec();
}

如何在我的应用程序中设置与 windows 使用的完全相同的字体?

Qt 版本:5.7.1

谢谢!

我的解决方案只有在您使用 Windows 时才有效。如果这不是故意的,只需使用预处理器!

简单的解决方案应该是使用 OS 函数。此代码应为您提供字体名称。

//please note that this requires minimum Windows 7, for older versions a small change is needed over preprocessors
#include<Windows.h>
std::wstring getSystemDefaultFontName() {
    NONCLIENTMETRICS ncm;
    ncm.cbSize = sizeof(ncm);
    HRESULT hr;
    hr = SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0);
    if (hr == 0)
        return std::wstring();
    return  std::wstring(ncm.lfMenuFont.lfFaceName); //There are different fonts for each section. I choose menu font but something else may be better?
}

对于 Qt 只需说:

QFont systemFont(QString::fromWCharArray(getSystemDefaultFontName().c_str()), 8, QFont::Bold, true);
QApplication::setFont(systemFont);

但是请记住,字体看起来仍然会略有不同,因为与 Windows.[ 相比,Qt 可能呈现不同的字体。 =23=]