Qt QTabWidget标签页左侧显示文字无法水平显示解决方案

 重写QProxyStyle

#pragma once


#include 
#include 
#include "CreateSteeing.h"
class QSteeing : public QProxyStyle
{
	Q_OBJECT

public:
	QSteeing();
	~QSteeing();

	//初始化
	void Init();

	/* sizeFromContents
	*  用于设置Tab标签大小
	* 1.获取原标签大小
	* 2.宽高切换
	* 3.强制宽高
	* 4.return
	* */
	QSize sizeFromContents(ContentsType type, const QStyleOption* option,
		const QSize& size, const QWidget* widget) const;

	/* drawControl
 *  画控件
 * 1.过滤CE_TabBarTabLabel
 * 2.选择状态下的背景绘制
 *      a.获取Rect
 *      b.保存旧的画笔
 *      c.设置新画笔
 *      d.画 Rect
 *      e.恢复旧的画笔
 * 3.设定Text对齐及选中/非选中状态下的Text颜色
 * 4.过滤CE_TabBarTab,对其进行绘制
 * */
	void drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const;




};

 

#include "QSteeing.h"
#include 
#include 


QSteeing::QSteeing()
{

}

QSteeing::~QSteeing()
{


}



QSize QSteeing::sizeFromContents(ContentsType type, const QStyleOption* option, const QSize& size, const QWidget* widget) const
{
	QSize s = QProxyStyle::sizeFromContents(type, option, size, widget);
	if (type == QStyle::CT_TabBarTab) {
		s.transpose();
		s.rwidth() = 120; // 设置每个tabBar中item的大小
		s.rheight() = 44;
	}
	return s;
}

void QSteeing::drawControl(ControlElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const
{
	if (element == CE_TabBarTabLabel) {
		if (const QStyleOptionTab* tab = qstyleoption_cast(option))
		{
			QRect allRect = tab->rect;

			if (tab->state & QStyle::State_Selected) {
				painter->save();
				painter->setPen(0x89cfff);
				painter->setBrush(QBrush(0x89cfff));
				QRect nrct = allRect.adjusted(6, 6, -6, -6);
				painter->drawRect(allRect.adjusted(6, 6, -6, -6));
				painter->restore();
			}
			QTextOption option;
			option.setAlignment(Qt::AlignCenter);
			if (tab->state & QStyle::State_Selected) {
				painter->setPen(0xf8fcff);
			}
			else {
				painter->setPen(0x5d5d5d);
			}

			painter->drawText(allRect, tab->text, option);
			return;
		}
	}

	if (element == CE_TabBarTab) {
		QProxyStyle::drawControl(element, option, painter, widget);
	}
}

#include "QSteeingUI.h"
#include "QSteeing.h"


QSteeingUI::QSteeingUI(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	//将标签页设置为左侧,但是会导致标签页文字方向为垂直显示需要改成水平显示,需要添加类实现
	ui.tabWidget->setTabPosition(QTabWidget::West);

	m_createSteeing = new CreateSteeing;

	ui.tabWidget->setAttribute(Qt::WA_StyledBackground);

	ui.tabWidget->insertTab(0, m_createSteeing, QString::fromLocal8Bit("创建设置"));

	ui.tabWidget->tabBar()->setStyle(new QSteeing);

	ui.tabWidget->tabBar()->setStyleSheet(
		" QTabBar::tab{height:100}"
		" QTabBar::tab{width:100}"
	);

}

QSteeingUI::~QSteeingUI()
{


}

效果:

Qt QTabWidget标签页左侧显示文字无法水平显示解决方案_第1张图片

 

你可能感兴趣的:(qt)