我正在从构造函数中动态地将Tabs添加到TabWidget。我已经能够添加选项卡,但无法为窗口小部件的窗格,选项卡设置样式。
如何向标签(栏)和标签(窗格)添加样式?选项卡的名称是动态的,而不是静态的。这是我的代码:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPixmap httpPix(":/rec/img/http_2.png");
ui->menuTabWidget->addTab(new Workspace(), QString("Projects"));
ui->menuTabWidget->addTab(new HistoricalRequests(), QString("History"));
ui->apiTabWidget->setStyleSheet("{background:#FFF}");
//ui->apiTabWidget->setPalette(*(new QPalette(Qt::green)));
//ui->apiTabWidget->tabBar()->setPalette(*(new QPalette(Qt::white)));
ui->apiTabWidget->addTab(new APITab(), httpPix, QString("New Test 1"));
}
答案 0 :(得分:1)
这是直接从设置标签样式的生产代码样式表中复制的。不幸的是,我不能分享截图,但它最有效!
请注意,MaintenanceBaseWActivity
是应用程序中一个窗口的名称,因此这些样式仅适用于该窗口中的选项卡。
MaintenanceBaseWActivity .QTabBar::tab {
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0.0 #666,
stop: 1.0 #aaa );
color: white;
padding: 0.4em;
margin:0;
height:1em;
min-width:5.7em;
max-width:5.7em;
width:5.7em;
border:0px;
border-top-left-radius:8px;
border-top-right-radius:8px;
}
MaintenanceBaseWActivity .QTabBar::tab:selected {
background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0.0 #bbb,
stop: 1.0 #ddd);
font-weight:bold;
color:black;
}
/*
MaintenanceBaseWActivity .QTabWidget::tab-bar {
width:1024px;
}
*/
MaintenanceBaseWActivity .QTabWidget::pane {
border-top: 8px solid #ddd;
}
编辑:为了回答您的评论,我发现不建议为每个小部件设置单独的样式表。最好在中央样式表中命名您的小部件或至少样式类(您可以使用对象名称),然后在启动时应用它。
以下是我用于从项目资源中应用中央样式表的确切代码:
QString fileToString(QString fn)
{
QFile file(fn);
if(file.open(QFile::ReadOnly)) {
QTextStream in(&file);
return in.readAll();
}
return "";
}
// Get the core app first
QCoreApplication *capp=static_cast<QCoreApplication *> QCoreApplication::instance());
// Then see if we can get a normal app (with UI and styles)
QApplication *app=qobject_cast<QApplication *>(capp);
if (nullptr!=app) {
// I am using a resource, so I just make bloody sure it is loaded (since this code might run from palces in the program that might not have resources loaded yet.
Q_INIT_RESOURCE(style); //My resource file is called "style.qrc" so please adapt this to whatever you are using.
// Time to load and set the stylesheet program wide. Please replace the path to the stylesheet you want,
app.setStyleSheet ( fileToString(":/style/style.qss"));
}