标签关闭按钮位置

时间:2012-10-30 10:29:14

标签: qt qtstylesheets qtabbar

我想在我的Qt应用中设置我的标签,如下所示:

enter image description here

我使用了以下样式表:

QTabBar{background-color: #fff; border-top: 0px;}
QTabBar::tab {
    border-image: url(:/New_UI/tab_inactive.png) 7 17 7 2;
    margin-left: 2px;
    border-right: 17px;
    border-top: 5px;
    border-bottom: 5px;
    font: 400 9.2pt "Segoe UI";
    color: #ccc;
    padding: 0px 13px 0px 5px;
    max-height: 26px;
 }

QTabBar::tab:selected, QTabBar::tab:hover {
    border-image: url(:/New_UI/tab_active.png) 6 17 6 2;
}

QTabBar::close-button {
    image: url(:/New_UI/tab_close.png);
    subcontrol-origin: padding;
    subcontrol-position: right; 
    width: 13px;
    height: 13px;

}

结果如下(关闭按钮位置不是我想要的):

enter image description here

我做错了什么?我怎么能得到我想要的结果?

5 个答案:

答案 0 :(得分:5)

编辑:我知道这篇文章很老,但我希望它可以帮助其他人。

经过几次测试后,我认为有一种方法可以做到这一点,但它没有使用Qt style sheets

  1. 对您的QTabWidget进行子类化,以便完全访问受保护的功能
  2. 创建自己的QWidgetQPushButton作为关闭按钮
  3. 使用样式表属性(例如margin-right
  4. 管理按钮的位置
  5. 将您的按钮添加到标签tabBar()->setTabButton(index, QTabBar::RightSide, closeButton);
  6. 我用于测试的代码:

    MyTab::MyTab(QWidget *parent) : QTabWidget(parent)
    {
    /// Create your button
    QPushButton *close = new QPushButton(this);
    
    // Add a tab
    addTab(new QWidget(), QIcon(), "Tab 1");
    setStyleSheet("QTabBar::tab { width : 150px;}");
    
    // Size and move your button
    close->setStyleSheet("max-height: 14px; max-width: 15px; margin-right: 50px;");
    
    // Add your button to the tab
    tabBar()->setTabButton(0, QTabBar::RightSide, close);
    }
    

    最后,在MainWindow中,我将自己的TabWidget添加到布局中:

    ui->layout->addWidget(new MyTab(this));
    

    结果:

    enter image description here

    但现在您必须通过连接按钮手动处理关闭操作并获取removeTab(index)电话的索引。

答案 1 :(得分:0)

我做的和你做的一样,这是我的样式表:

QTabBar::close-button{
    image:url(:tabclose.png); 
    margin-right:4px;
}

不要使用“width”和“height”属性,这两个在这里不起作用,在子控件上设置“image:url()”隐式设置子控件的宽度和高度(除非图像在SVG)。

使用“margin-right”属性控制距选项卡右边缘的距离;

答案 2 :(得分:0)

添加自定义按钮是一个很好的答案。但如果你使用margin来决定关闭按钮的位置,关闭按钮的鼠标区域将会出现异常,所以我在一个小部件中添加了一个SpacerItem和按钮,最后将这个小部件添加到TabWidget。

void TabBarCloseable::tabInserted(int index)
{
    QWidget *widget = new QWidget(this);
    QHBoxLayout *layout = new QHBoxLayout(this);
    widget->setLayout(layout);

    QToolButton *closeBtn = new QToolButton(this);
    layout->addWidget(closeBtn);
    layout->insertSpacing(1, 15);
    closeBtn->setStyleSheet("max-height: 16px; max-width: 16px;");

    this->setTabButton(index, QTabBar::RightSide, widget);

    QTabBar::tabInserted(index);
}

答案 3 :(得分:0)

您的填充错误

enter image description here

顶部

QTabBar::tab {
    min-width: 25ex;
    padding: 10px 50px 10px 10px;
}

按钮

QTabBar::tab {
    min-width: 25ex;
    padding: 10px 0px 10px 10px;
}

答案 4 :(得分:-1)

这是一个纯粹的样式表解决方案,无需手动创建按钮:

QTabBar::close-button {
    image: url(:/tab-close.png);
    padding-left: -13px;
}

如果检查Qt源,图像绘制代码仅使用填充值,而不使用边距值。

相关问题