Rewrite QComboBox, implement custom QFontComboBox, add custom fonts, display font styles

During the development process, there is a requirement to add a font selection box. This is simple. I can directly use QFontComboBox to solve it. But my requirement is that fonts do not use system fonts, but use our custom font library. Later I tried to use QComboBox to solve it, but this ghost can't change the font style of a single item alone, forget it, just write it by yourself, not much to say, the code:


class CFontComboBox : public QComboBox {
    Q_OBJECT
private:
    QListWidget * mFontList;
public:
    CFontComboBox(QWidget * parent = nullptr);
    void addFont(QString famil);
    void addFonts(QStringList famils);
protected:
    void wheelEvent(QWheelEvent ) override;
};

.cpp文件

CFontComboBox::CFontComboBox(QWidgetparent) :
    QComboBox(parent)
{
    mFontList = new QListWidget(this);
    setModel(mFontList->model());
    setView(mFontList);
    mFontList->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    setStyleSheet("QComboBox{combobox-popup:0;}");
    setMaxVisibleItems(5);
}
void CFontComboBox::wheelEvent(QWheelEvent * event) {
}
void CFontComboBox::addFont(QString famil) {
    auto item = new QListWidgetItem(famil);
    QFont font;
    font.setFamily(famil);
    item->setFont(font);
    QIcon icon(":icons/T.png");
    item->setIcon(icon);
    mFontList->addItem(item);
}
void CFontComboBox::addFonts(QStringList famils) {
    for (auto famil : famils)
    {
        addFont(famil);
    }
}

You're done, not much to say, the picture above:
Choose font.png

There is no custom icon in the front. This is what I asked the UI to design for me, and I can use it if I want it. Not much to say, the picture above:
Icon.png

In order to prevent someone from not understanding it, let me explain it. If you understand it, skip it.
setView() replaces our View, and then we are operating on our View.

setStyleSheet(“QComboBox{combobox-popup:0;}”);
setMaxVisibleItems(5);

This three is to set the maximum number of display and scroll bars, no can not set
me rewrite wheelEvent method, I do not want to let the user to change the font by mouse, no can not rewrite,
final AddFont and addFonts don’t need to explain, just use these two methods to add fonts.
If you feel that my example can help you, remember to pay attention, and I will update Qt skills and methods frequently in the future
.

Guess you like

Origin blog.csdn.net/weixin_41191739/article/details/111564654