动态展开QTabBar [英] Expand QTabBar dynamically

查看:418
本文介绍了动态展开QTabBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过QLineEdit动态插入标签,工作正常。要填充屏幕的整个宽度(800像素),我使用自己的eventFilter展开标签页:

I'm inserting tabs via QLineEdit dynamically which works fine. To fill the whole width of the screen (800px) I'm expanding the tabs using my own eventFilter:

tabs.h

class ResizeFilter : public QObject
{
    QTabBar *target_tabs;

public:
    ResizeFilter(QTabBar *target_tabs) : QObject(target_tabs), target_tabs(target_tabs) {}

    bool eventFilter(QObject *object, QEvent *event)
    {
        if (object == target_tabs) {
            if (event->type() == QEvent::Resize)
            {
                // The width of each tab is the width of the tabbar / # of tabs.
                target_tabs).arg(target_tabs->size().width()/target_tabs->count()));
            }
        }
        return false;
    }
};

class tabs : public QWidget
{
    Q_OBJECT

private:
    QTabBar *cells;
};

tabs.cpp

void tabs::changeTabs(int value)
{
    tabs->installEventFilter(new ResizeFilter(tabs));

    if (tabs->count() < value)
        tabs->insertTab(tabs->count(), QIcon(QString("")), QString::number(value));
}

运行应用程序后,一个选项卡始终可见并正确展开。如上所述,最大宽度设置为800像素。添加新的选项卡工作正常,但调整大小事件弄乱了尺寸标注。假设我添加了第二个标签,它在第一个标签旁边显示800px,而不是在800像素(每个400像素/ 400像素)内缩放两个标签。

One tab is always visible and expanded correctly after running the app. As said the maximum width is set to 800 pixels. Adding a new tab is working fine but the resize event messes up the dimensioning. Lets say I'm adding a second tab it's showing 800px next to the first one instead of scaling both tabs within the 800px (400 / 400 px each).

像这样:
插入错误

当它实际应该看起来像这样:
它应该是

When it actually should look like this: how it's supposed to be

我在这里做错了什么?

推荐答案

您正在设置选项卡上的大小,而不是在QTabBar。

You are setting a size on the tab, not on the QTabBar. So obviously the new tab(s) will take the set width, until a resize happens.

你可以继承 QTabBar 并实现 resizeEvent tabInserted ,这也使得您的 eventFilter 冗余。

You can just inherit QTabBar and implement both resizeEvent and tabInserted, which also makes your eventFilter redundant.

示例代码:

class CustomTabBar : public QTabBar
{
public:
    CustomTabBar(QWidget *parent = Q_NULLPTR)
        : QTabBar(parent)
    {
    }

protected:
    void resizeEvent(QResizeEvent *e) Q_DECL_OVERRIDE
    {
        /*resize handler*/
    }

    void tabInserted(int index) Q_DECL_OVERRIDE
    {
        /*new tab handler*/
    }

    void tabRemoved(int index) Q_DECL_OVERRIDE
    {
        /*tab removed handler*/
    }
};

这篇关于动态展开QTabBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆