I am new to qt and I want to know how to make a dynamic menu. I did get it to make new submenus but I don't know how I can implement the "triggered() function" of these dynamic made submenus, so that I have access to what happens if I want to click on such a new submenu.
Here what I have so far (with: vector<QString> = vec;
and some .ui Window named "New_Window")
in mainwindow.cpp
in some function:
QMenu *menu = this->menuBar()->addMenu("Chat Members");
for (int i = 0; i < vec.size(); i){
QString name = vec.at(i);
QAction *act = menu->addAction(name);
New_Window* new_window = new New_Window;
QObject::connect(act,SIGNAL(triggered()),
new_window,SLOT(actionReaction()));
}
CodePudding user response:
here is an example of how a signal slot with a dynamic interface works ,
class A
is created after starting the program, then the user clicks on a button from class A
, for example, a class A
is created many times and we need to determine from what object we get a signal
to press the button, so
class A : public QMainWindow
{
Q_OBJECT
public:
A(QWidget *parent = nullptr);
~A();
void setID(const int id);
void getId() const;
signals:
void onButtonPress(int ID);
private:
int mID;
};
here we create a new class A
and store it in the vector
in such a way,
QVector<A*> mCreatingClassA;
void createNewClassA
{
QVector<A*> mCreatingClassA;
....
A* a = new A();
int id = // create your unique ID
a->setId(id);
connect(a,SIGNAL(onButtonPress(int)),this,SLOT(onyourSlot(int)));
mCreatingClassA.push_back(a);
....
}
detect the object from which the signal
was received)
void onyourSlot(int ID)
{
for (int i = 0; i < mCreatingClassA.size(); i) {
if(mCreatingClassA[i]->getId()==ID)
{
mCreatingClassA[i] // received a signal from this object
}
}
}