[Qt-interest] QHeaderView: built-in RMB menu to show/hide columns?
Daniel Franke
franke.daniel at gmail.com
Fri Feb 11 20:49:41 CET 2011
On Friday 11 February 2011 17:50:09 Robert Hairgrove wrote:
> Alternatively, you could reimplement the protected mousePressEvent() in
> your header view subclass. That might actually be the easiest way to go.
Robert, thanks for the pointer.
As I couldn't find a simple example (and didn't want to dig through the KDE
sources), find my working implementation below. Not sure if the actions are
deleted by the menu or if they are leaked, though.
Something like this could be an addition for future releases, maybe?
Cheers
Daniel
--
class MyHeaderView : public QHeaderView {
Q_OBJECT
public:
MyHeaderView(QWidget *parent = 0);
protected slots:
void toggleSectionVisibility(int section);
protected:
void mousePressEvent(QMouseEvent *e);
};
MyHeaderView::MyHeaderView(QWidget *parent)
: QHeaderView(Qt::Horizontal, parent) {
}
void MyHeaderView::mousePressEvent(QMouseEvent *e) {
if (e->button() == Qt::RightButton) {
QMenu menu;
QSignalMapper mapper;
QAbstractItemModel *m = model();
for (int col = 0; col < model()->columnCount(); ++col) {
QAction *action = new QAction(&menu);
action->setText(model()->headerData(col, Qt::Horizontal).toString());
action->setCheckable(true);
action->setChecked(!isSectionHidden(col));
connect(action, SIGNAL(triggered()), &mapper, SLOT(map()));
mapper.setMapping(action, col);
menu.addAction(action);
}
connect(&mapper, SIGNAL(mapped(int)),
this, SLOT(toggleSectionVisibility(int)));
menu.exec(e->globalPos());
}
QHeaderView::mousePressEvent(e);
}
void MyHeaderView::toggleSectionVisibility(int section) {
setSectionHidden(section, !isSectionHidden(section));
}
More information about the Qt-interest-old
mailing list