大型门户网站开发公司,有app怎么做网站,家具设计师培训,国外创意型网站设计使用QTabWidget#xff0c;给每个tab添加了图标之后#xff0c;文字和图标之间有间距#xff0c;没有完美居中显示。
遇到此问题#xff0c;尝试了多种办法#xff0c;均不理想#xff0c;最终自定义QTabBar#xff0c;重绘tab#xff0c;完美解决。
#include QT…使用QTabWidget给每个tab添加了图标之后文字和图标之间有间距没有完美居中显示。
遇到此问题尝试了多种办法均不理想最终自定义QTabBar重绘tab完美解决。
#include QTabBar
#include QStylePainterclass MyTabBar : public QTabBar {
public:MyTabBar(QWidget *parent nullptr) : QTabBar(parent){}protected:void paintEvent(QPaintEvent *) override{QStylePainter painter(this);for (int index 0; index this-count(); index) {QStyleOptionTab opt;initStyleOption(opt, index);// 计算图标和文字的长度含间距int iconTextWidth opt.iconSize.width() opt.fontMetrics.horizontalAdvance(opt.text) 4; // 4 是图标和文字的间距int x (opt.rect.width() - iconTextWidth) / 2 opt.rect.width() * index;painter.save();// 指定各状态下的按钮状态if (opt.state QStyle::State_Selected) { // 按下状态painter.setPen(QColor(255, 255, 255));painter.fillRect(rect, QColor(31, 68, 133));} else if (opt.state QStyle::State_MouseOver) { // 鼠标停留状态painter.setPen(QColor(255, 255, 255));painter.fillRect(rect, QColor(33, 72, 141));} else if (!(opt.state QStyle::State_Enabled)) { // 禁止状态painter.setPen(QColor(255, 255, 255, 153));painter.fillRect(rect, QColor(84, 123, 192));} else { // 正常状态默认painter.setPen(QColor(255, 255, 255));painter.fillRect(rect, QColor(41, 90, 176));}QRect iconRect(x, (opt.rect.height() - opt.iconSize.height()) / 2,opt.iconSize.width(), opt.iconSize.height());painter.drawPixmap(iconRect, opt.icon.pixmap(opt.iconSize));QRect textRect(iconRect.right() 4, 0,opt.rect.width() * (index 1) - iconRect.right() - 4,opt.rect.height());painter.drawText(textRect, Qt::AlignVCenter | Qt::AlignLeft, opt.text);painter.restore();}}
};
调用
ui-tabWidget-setTabBar(new MyTabBar(this));