简体   繁体   中英

Qt cant open new window

I have a program that in the main opens a window with user list and 2 buttons, when one button is pressed it should close/hide the main window, and open a new window (in this case MarkdownEditorUi class).

But when I do the .show() comand, the new window does not appear, and I don t know why, int the main (opening the main window works), but in the main window opening a second window does not work.

  • I do in the method: FirstCplusPlusQt5Program::buttonMarkdownAction()

    CreateEditMarkdownNoteUi markdownEditor; markdownEditor.show(); //show markdown editor window this->hide();

But the markdownEditor dont/open show a new window. And i know in the debug that the code is executed.

Am i doing something wrong? It was based in windows created in the Qt Creator. I should work.

Also: when the new window is invoked in the main, it works, and the code is exactly the same. I dont understand why it doesn't work in the main window, but works in the void main();

Code

Main

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

    RuntimeContainer r(20);
    r.insertLog("Start main","Starting everything ", Log::PROGRAM_STARTUP);

    cout << "Fist log inserted in main memory: \n> Name--> " << r.getLogList().getLogByIndex(0).getName().toStdString() << " \n--> Description: "<< r.getLogList().getLogByIndex(0).getDescription().toStdString();


    QApplication app(argc, argv);
    FirstCplusPlusQt5Program w; 
    w.setRunTimeContainer(r);
    w.show();           //open the main window



    return app.exec();

}

Main window

在此处输入图片说明

    #include "firstcplusplusqt5program.h"
#include "ui_firstcplusplusqt5program.h"

#include <QString>

#include "UC/CreateCategory/UI/createCategoryUi.h"



/**
 * @brief window constructor
 * 
 * @param parent p_parent:...
 */
FirstCplusPlusQt5Program::FirstCplusPlusQt5Program(QWidget *parent) : QMainWindow(parent), ui(new Ui::FirstCplusPlusQt5Program){
    ui->setupUi(this);


    //test();

    /**
     *  connection of the button when its pressed with the method "buttonMarkdownAction()"
     **/
    connect(ui->qPushButtonMarkdown, SIGNAL (clicked()),this,SLOT (buttonMarkdownAction()));
    connect(ui->qPushButtonPlantUml, SIGNAL (clicked()),this,SLOT (buttonPlantUmlAction()));

}

/**
 * @brief default destructor
 * 
 */
FirstCplusPlusQt5Program::~FirstCplusPlusQt5Program(){
    delete ui;
}




/**
 *  
 * @brief when button pressed opens markdown editor, is a private slot
 * @details markdown editor is a new window. Validates if user is selected
 */
void FirstCplusPlusQt5Program::buttonMarkdownAction(){
    if (ui->qListWidgetUserList->selectedItems().size() > 0){       //if user list have selected user
        //do things
        QString s = ui->qListWidgetUserList->selectedItems()[0]->text();   //gets selected user name

        if (s.contains(QRegExp(USER_NAME_REGEX_DEFAULT))){      //VALIDATE USER name, database may be currompted
            User userToLogOn = this->r.getUserList().findUser(s);

            cout << "User: " << userToLogOn.getName().toStdString() << " ==> Email " << userToLogOn.getEmail().toStdString() << endl; //FOR TESTING
            CreateEditMarkdownNoteUi markdownEditor;
            markdownEditor.show();          //show markdown editor window
            this->hide();       //hide current window
            cout << "Test";     //FOR TESTING
        }
    }else{
        //error, informs the user from error
        noUserSelected("No user selected!!","Please select user", "No save the notes in differents login locations is needed a user.");

    }
}

New window to open

THIS WINDOW OPENS WHEN EXECUTED IN THE MAIN, AND THE CODE IS EXACTLY THE SAME IN THE PREVIEWS CODE

在此处输入图片说明

Cpp
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
    <class>CreateEditMarkdownNoteUi</class>
    <widget class="QMainWindow" name="CreateEditMarkdownNoteUi">
        <property name="geometry">
            <rect>
                <x>0</x>
                <y>0</y>
                <width>800</width>
                <height>600</height>
            </rect>
        </property>
        <property name="windowTitle">
            <string>CreateEditMarkdownNoteUi</string>
        </property>
        <widget class="QWidget" name="centralwidget"/>
        <widget class="QMenuBar" name="menubar">
            <property name="geometry">
                <rect>
                    <x>0</x>
                    <y>0</y>
                    <width>800</width>
                    <height>23</height>
                </rect>
            </property>
        </widget>
        <widget class="QStatusBar" name="statusbar"/>
    </widget>
    <resources/>
    <connections/>
</ui>
.h
 #ifndef CREATEEDITMARKDOWNNOTEUI_H #define CREATEEDITMARKDOWNNOTEUI_H #include <QMainWindow> namespace Ui { class CreateEditMarkdownNoteUi; } class CreateEditMarkdownNoteUi : public QMainWindow { Q_OBJECT public: explicit CreateEditMarkdownNoteUi(QWidget* parent = 0); ~CreateEditMarkdownNoteUi(); private: Ui::CreateEditMarkdownNoteUi* ui; }; #endif // CREATEEDITMARKDOWNNOTEUI_H 
.ui
 <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>CreateEditMarkdownNoteUi</class> <widget class="QMainWindow" name="CreateEditMarkdownNoteUi"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>600</height> </rect> </property> <property name="windowTitle"> <string>CreateEditMarkdownNoteUi</string> </property> <widget class="QWidget" name="centralwidget"/> <widget class="QMenuBar" name="menubar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>800</width> <height>23</height> </rect> </property> </widget> <widget class="QStatusBar" name="statusbar"/> </widget> <resources/> <connections/> </ui> 

Cmake list (similar to make, or qmake, with list of cpp files and .ui to run/compile)

 cmake_minimum_required(VERSION 2.8.11) project(FirstCplusPlusQt5Program) # Find includes in corresponding build directories set(CMAKE_INCLUDE_CURRENT_DIR ON) # Instruct CMake to run moc automatically when needed. set(CMAKE_AUTOMOC ON) # Find the QtWidgets library find_package(Qt5Widgets REQUIRED) # # # @author : josemiguel443@gmail.com = add src file of .cpp of used/compiled #classes # # # set( # PROJECT DEPENDENCIES firstcplusplusqt5program_SRC src/main.cpp src/firstcplusplusqt5program.cpp # DOMAIN src/Domain/Category.cpp src/Domain/User/user.cpp src/Domain/note.cpp #DOMAIN LIST src/Domain/List/categorylist.cpp # LOG src/RuntimeLog/log.cpp src/RuntimeLog/loglist.cpp # DOMAIN LIST src/Domain/List/noteList.cpp src/Domain/List/userList.cpp # UTILS src/Utils/utils.cpp # UC src/UC/CreateCategory/UI/createCategoryUi.cpp src/UC/CreateNoteWithMarkdown/UI/createeditmarkdownnoteui.cpp #note used yet # PERSISTENCE src/Persistence/InMemory/runtimecontainer.cpp ) # Create code from a list of Qt designer ui files. #set(CMAKE_AUTOUIC ON) # use this if you have CMake 3.x instead of the following # # # @author : josemiguel443@gmail.com = add src file of .ui for QT # # # qt5_wrap_ui(firstcplusplusqt5program_SRC src/firstcplusplusqt5program.ui src/UC/CreateCategory/UI/createCategoryUi.ui #src/UC/CreateNoteWithMarkdown/createeditmarkdownnoteui.ui #note used yet ) # Tell CMake to create the helloworld executable add_executable(firstcplusplusqt5program ${firstcplusplusqt5program_SRC}) # Use the Widgets module from Qt 5. target_link_libraries(firstcplusplusqt5program Qt5::Widgets) # Install the executable install(TARGETS firstcplusplusqt5program DESTINATION bin) 

Output

 user19User: user5 ==> Email user5@gmail.com Test *** Finished *** 

I already tried the solutions given in another threads of stack overflow and dont work and i dont understand why ( How to open a new window from the main window in Qt? ).

Thank you for the help in advance

The problem is the object is getting out of scope.

In main function the window open and stills openned due the event loop app.exec(); . It's preventing reaches the end of the scope of your main function until the program ends and the event loop returns the exit code.

To work around this problem without too much changes in your code you can create the class with new and get rid of the problems with scope, set a parent to this class to enable auto delete or set explicitly the setAttribute(Qt::WA_DeleteOnClose); with the same purpose.

Also remember that if all windows are closed and QApplication::quitOnLastWindowClosed() == true; the entire application will be closed, so if necessary call QApplication::setQuitOnLastWindowClosed(false); and exit your application explicitly using QApplication::quit(); for example:

CreateEditMarkdownNoteUi *markdownEditor = new CreateEditMarkdownNoteUi(this);
markdownEditor->show(); 

You use: ui->setupUi(this);

If you want your ui-design be set up on a new window, this should be this new window. See https://stackoverflow.com/a/12182145/4599792 .

I doubt however if it is smart or possible to have two windows of QMainWindow type within the same application. So let your ui-design run within a QWidget window , but not within QMainWindow window .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM