H
H
hitakiri2022-01-05 08:09:05
Qt
hitakiri, 2022-01-05 08:09:05

How to add widget to QMainWindow?

You need to add the menuBar widget to the finished program. The widget is nicely added to the MainWindow. But you need to make sure that the logic for adding the menu is in a separate file. I do this:
topMenu.h :

#ifndef TOPMENU_H
#define TOPMENU_H

#include <QMainWindow>
#include <QApplication>

class topMenu : public QWidget {

    Q_OBJECT

public:
    topMenu(QWidget *parent = nullptr);
    void showTopMenu();
};

#endif // TOPMENU_H


topMenu.cpp:
#include "topmenu.h"
#include <QMenu>
#include <QMenuBar>

topMenu::topMenu(QWidget *parent) : QWidget(parent) {
    void showTopMenu();
}

void topMenu::showTopMenu() {
    QAction *newProject = new QAction("&Новый проект");

    QMenu *file;
    QMenuBar *menu;

    file = menu->addMenu("&Меню");
    file->addAction(newProject);
}


mainwindow.h :
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include "topmenu.h"
#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    topMenu *mmMenu;
};

#endif // MAINWINDOW_H


main.cpp:
#include "mainwindow.h"
#include "topmenu.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;

    topMenu mmMenu;
    mmMenu.showTopMenu();
    w.show();


    return a.exec();
}


Accordingly, the result is zero, there are no errors, but the menu does not show either ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacob E, 2022-01-05
@Zifix

And where did you get the idea that you now have the main window and the menu widget somehow connected? And if you have ten windows, how is the program supposed to know which one you want to add a menu to?
Hint: where did you create the object, in what memory area?
Take any book on Qt, a book on C++, and figure out the basics. You can, of course, also by typing, asking on the forum every time, but once it's a hundred longer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question