[Qt-interest] QHeaderView: built-in RMB menu to show/hide columns?
Robert Hairgrove
evorgriahr at hispeed.ch
Fri Feb 11 21:23:04 CET 2011
On Fri, 2011-02-11 at 20:49 +0100, Daniel Franke wrote:
> 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));
> }
Looks good!
Taking a quick look at the Menus Example in QtAssistant, I noticed that
they override this instead of mousePressEvent:
QWidget::contextMenuEvent(QContextMenuEvent *event)
But either way is probably OK.
More information about the Qt-interest-old
mailing list