我正在从构造函数中动态地将选项卡添加到TabWidget。我已经能够添加选项卡,但无法为窗格设置样式。
。如何将样式添加到选项卡(bar)和Tab(窗格)中?标签的名称是动态的,而不是静态的。这是我的代码:
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"));
}
这是从样式选项卡的生产代码样式上直接复制的。不幸的是,我无法共享屏幕截图,但最有效!
请注意,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"));
}