0

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));
}

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).

It looks like this: wrong insertion

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

What am I doing wrong here?

user861594
  • 5,733
  • 3
  • 29
  • 45
MichaW.
  • 37
  • 5

1 Answers1

2

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.

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

Sample code:

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*/
    }
};
JefGli
  • 781
  • 3
  • 15
  • Thanks for your answer! I like the idea but I'm pretty sure that I don't exactly know how to do so.. Could you please give me a slight example? – MichaW. Jun 08 '16 at 09:56
  • @MichaW. Added Sample code, but I suggest reading up on C++ and inheritance. – JefGli Jun 08 '16 at 10:08