PDA

View Full Version : Adding buttons on the tab part of a tabwidget



forrestfsu
18th December 2006, 20:21
I was wondering if anyone has any idea how I should go about adding an "X" button onto certain tabs of my tabWidget. I am not talking about adding a button onto the body of the tabwidget. I'm talking about actually adding a clickable image inside the tab.

wysota
18th December 2006, 21:44
Subclass QTabBar and reimplement its mousePressEvent. Check the click coordinates there and act if it happened inside the "button". You might also want to reimplement other events to make the button appear "clickable".

forrestfsu
20th December 2006, 17:52
Wysota, thanks for the tip! I got the basics of it working perfect. I figured I would show part of my code just incase anyone needs it in the future. Please let me know if you see any potential problems with it:



class TabWidget : public QTabWidget
{
public:
TabWidget(Widget *parent=0);
}
class Tab : public QTabBar
{
Q_OBJECT
public:
Tab(QWidget *parent=0);
protected:
void paintEvent(QPaintEvent *event);
QSize tabSizeHint(int index) const;
void mousePressEvent(QMouseEvent *event);
private:
QWidget *pParent;
TabWidget *tabWidget;
}

Tab::Tab(QWidget *parent) : QTabBar(parent)
{
pParent = parent;
tabWidget = (TabWidget*) pParent;
}

void Tab::paintEvent(QPaintEvent *event)
{
QTabBar::paintEvent(event);
QPainter p(this);
QRect r;
int count = this->count() -1;
for (int i=0; i< count; i++)
{
r = this->tabRect(i);
p.drawPixmap(r.right()-22, r.top()+5, QPixmap(":/icons/x.png");
}
r = this->tabRect(count);
p.drawPixmap(r.left()+4, r.top()+5, QPixmap(":/icons/add.png"));
}

void Tab::tabSizeHint(int index) const
{
QSize size = QTabBar::tabSizeHint(index);
if (tabWidget->tabText(index) == "")
size.setWidth(size.width() + 2);
else
size.setWidth(size.width() + 32);
return size;
}

void Tab::mousePressEvent(QMouseEvent *event)
{
QRect r;
for (int i=0; i < this->count()-1; i++)
{
r = this->tabRect(i);
if ((event->x() >= r.right()-22) && (event->x() <= r.right()-8))
{
...
tabWidget->removeTab(i);
return;
...
}
}
QTabBar::mousePressEvent(event);
}

TabWidget::TabWidget(QWidget *Parent) : QTabWidget(parent)
{
Tab *bar = new Tab(this);
setTabBar(bar);
}


Thanks!