共计 1341 个字符,预计需要花费 4 分钟才能阅读完成。
在开发的过程中,有个需要,是增加一个字体抉择框,这个简略,我能够间接用了 QFontComboBox 解决,然而我的需要是字体不必零碎字体,而是用咱们自定义增加的字体库,起初我尝试用 QComboBox 解决,然而,这个鬼货色却不能独自扭转独自 item 的字体款式,算了,间接本人写吧,话不多说,上代码:
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); | |
} | |
} |
功败垂成,话不多说,上图:
自定义的是没有后面是没有那个图标的,这是我让 UI 给我设计的,想要的能够拿去用,话不多说,上图:
为了避免有人看不懂,我还是解释一下吧,看懂的间接跳过,
setView(), 是把咱们的 View 替换下来,而后咱们在对咱们的 View 进行操作,
setStyleSheet(“QComboBox{combobox-popup:0;}”); | |
setMaxVisibleItems(5); |
这三句是为了设置滚动条和最大显示个数,不须要的能够不必设置
我这里重写了 wheelEvent 办法,是为了我不想不让用户通过鼠标去扭转字体,不须要的能够不重写,
最初 addFont 和 addFonts 不必解释了吧,间接用这两个办法去增加字体都行了
如果感觉我的实例能够帮忙到你,记得关注,当前会常常更新 Qt 技巧和办法
话不多说,下课
正文完