在 GUI 编程时,经常会需要一些小图标,如果直接去网上找现成的,可能有版权问题,自己做的话又麻烦,耽误时间。其实 Qt 有很多内置的图标可供我们使用,使用 QStyle::standardIcon(SEO靠我) 即可获得这些内置图标。
先大概介绍一下 QStyle 类,它是一个抽象基类,封装了 GUI 的外观。Qt 包含一组 QStyle 子类,用于模拟 Qt 支持的不同平台的样式(QWindowsStylSEO靠我e、QMacStyle、QMotifStyle 等)。Qt 的内置 widget 使用 QStyle 来执行几乎所有的绘图,确保它们看起来与原生 widget 完全一样。
我们可以使用 QApplicaSEO靠我tion::setStyle() 函数设置整个应用程序的样式。也可以使用QWidget::setStyle() 函数设置某个 widget 的样式。 如果没有指定样式,Qt 会为用户的平台或桌面环境选SEO靠我择最合适的样式。
言归正传,QStyle::standardIcon() 文档如下:
QIcon QStyle::standardIcon ( StandardPixmap standardIcon, cSEO靠我onst QStyleOption * option = 0, const QWidget * widget = 0 ) constReturns an icon for the given stanSEO靠我dardIcon.
The standardIcon is a standard pixmap which can follow some existing GUI style or guidelineSEO靠我. The option argument can be used to pass extra information required when defining the appropriate iSEO靠我con. The widget argument is optional and can also be used to aid the determination of the icon.
WarniSEO靠我ng: Because of binary compatibility constraints, this function is not virtual. If you want to providSEO靠我e your own icons in a QStyle subclass, reimplement the standardIconImplementation() slot in your subSEO靠我class instead. The standardIcon() function will dynamically detect the slot and call it.
This functioSEO靠我n was introduced in Qt 4.1.
其中 StandardPixmap 是一个枚举,描述了可用的 pixmap,范围是 [0, 69],具体见:enum QStyle::StandardSEO靠我Pixmap。
我们来写个测试程序,看下这些内置图标在不同的样式下是什么样子。
代码下载链接:Qt_build_in_icons,关键代码为:
void Widget::on_cbStyle_activatSEO靠我ed(const QString &style) {QApplication::setStyle(style);ui->tableWidget->clear();ui->tableWiSEO靠我dget->setRowCount(7);ui->tableWidget->setColumnCount(10);int IconIndex = 0;for (int row = 0; row < uSEO靠我i->tableWidget->rowCount(); row++){for (int col = 0; col < ui->tableWidget->columnCount(); col++){QISEO靠我con icon = QApplication::style()->standardIcon((QStyle::StandardPixmap)IconIndex);QTableWidgetItem *SEO靠我item = new QTableWidgetItem(icon, QString::number(IconIndex));ui->tableWidget->setItem(row, col, iteSEO靠我m);IconIndex++;}} }结果如下:
我用的是 window 10 系统,默认是 windowsvista 样式,内置图标:
其他样式的 Qt 内置图标为:
Windows:
WindSEO靠我owsXP:
Motif:
CDE:
Plastique:
Cleanlooks:
网站备案号:浙ICP备17034767号-2