簡體   English   中英

從 QFontDatabase 設置 QFont 將所有標簽設置為等寬字體? Qt C++

[英]Setting QFont from QFontDatabase sets all labels to monospaced font? Qt C++

我正在嘗試將一個 QLabel 設置為等寬字體。 默認情況下,我在設計器中將所有其他標簽設置為“Arame-Regular”。 通常,嘗試在設計器中將我的任何標簽設置為“Arame-Mono”(等寬字體)都不起作用。 他們保持規律。

在我的 mainwindow.cpp 中的這段代碼之后,應用程序中的每個 label 都變為等寬:

    QFontDatabase::addApplicationFont("/path/to/the/fonts/Arame-Mono.ttf");
    QFont monospace("Arame-Mono");
    ui->labelFontTest->setFont(monospace);

這解決了部分問題,我猜可以使用等寬字體,但我不希望應用程序中的每個 label 都設置為等寬字體。 我怎樣才能只解決這個特定的 label 以對其應用等寬字體,並保留所有其他 label 的情況?

另一個副作用是我在啟動時收到此消息:

qt.qpa.fonts: Populating font family aliases took 159 ms. Replace uses of missing font family "Arame-Mono" with one that exists to avoid this cost.

我都在我的 Mac 上本地安裝了 fonts 並添加到 my.pro 文件中。 fonts 位於項目目錄內的 fonts 文件夾中:

DISTFILES += \
    Fonts/Arame-Mono.ttf \
    Fonts/Arame-Regular.ttf \

任何幫助表示贊賞!

我創建了一個簡單的演示; 它顯示了三個標簽,其中只有最后一個被手動設置為等寬:

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

    using QFD = QFontDatabase;
    if (QFD::addApplicationFont(QStringLiteral(":/Roboto/Roboto-Regular.ttf")) == -1) {
        qWarning() << "Failed to load Roboto-Regular.ttf";
    }
    if (QFD::addApplicationFont(QStringLiteral(":/Roboto_Mono/RobotoMono-Regular.ttf")) == -1) {
        qWarning() << "Failed to load RobotoMono-Regular.ttf";
    }

    QFont regular("Roboto");
    QApplication::setFont(regular);

    MainWindow w;
    w.show();

    return a.exec();
}
    QFont mono("RobotoMono");
    ui->label_3->setFont(mono);

這完美無缺。 在您的情況下,我建議main為應用程序設置常規字體。 然后僅在需要時使用等寬的。 另外,請記住,如果您計划發布應用程序,您應該使用QtResources ( .qrc ) 文件將 fonts 嵌入到可執行文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM