问题
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?
回答1:
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*/
}
};
来源:https://stackoverflow.com/questions/37697666/expand-qtabbar-dynamically