Template function
-
In .cpp file I have this template function:
template <typename M, typename N> void MainWindow::showMenu(M m, N n) { QSize size = m->sizeHint(); m->popup(n->mapToGlobal(QPoint(0,0-size.height()))); }
where
· m = QMenu
· n = QPushPuttonIn what form I should declare this function in the header file?
Thanks in advanve
-
What about MainWindow.h ?
Also since all QWidgets are QObjects, you dont need templates for most GUI operations.
-
connect(sel, SIGNAL(released()), this, SLOT(showMenu(QMenu, QPushButton))); void MainWindow::showMenu(QMenu *m, QPushButton *pb) { QSize size = m->sizeHint(); m->popup(pb->mapToGlobal(QPoint(0,0-size.height()))); }
Doesn't work
-
@UnitScan said in Template function:
Hi
That is because the released() signal DO NOT have QMenu* and QPushButton * parameters.You cannot invent new parameters for a signal.
You can define new signals though.http://doc.qt.io/qt-5/signalsandslots.html
also note that connect returns true if connect works.
so
qDebug() << "tcheck:" << connect(xxx) to see if they work.
-
SOLVED
void MainWindow::showMenu() { QPushButton *pb = qobject_cast<QPushButton*>(sender()); QMenu* m = qobject_cast<QMenu*>(pb->children().at(0)); QSize size = m->sizeHint(); m->popup(pb->mapToGlobal(QPoint(0,0-size.height()))); }
-
Hi you should check both pb an m for not being null :)
-
since I hate
sender()
andpb->children().at(0)
is even less robust I suggest (assuming you declaredQMenu* MainWindow::m
):connect(sel, &QPushButton::released, [=]()->void{ const QSize size = m->sizeHint(); m->popup(sel->mapToGlobal(QPoint(0,-size.height()))); });
P.S.
Looking at this functionality, are you sure QToolButton is not a better choice? seeQToolButton::setMenu
4/7