c++ - Qt打不开新窗口

标签 c++ qt user-interface

我有一个程序,主要打开一个带有用户列表和 2 个按钮的窗口,当按下一个按钮时,它应该关闭/隐藏主窗口,并打开一个新窗口(在本例中为 MarkdownEditorUi 类)。

但是当我执行 .show() 命令时,新窗口没有出现,我不知道为什么,int main(打开主窗口有效),但在主窗口中打开第二个窗口没有工作。

  • 我在方法中做:FirstCplusPlusQt5Program::buttonMarkdownAction()

    CreateEditMarkdownNoteUi markdownEditor; markdownEditor.show();//显示 Markdown 编辑器窗口 这->隐藏();

但是 markdownEditor 不/打开显示一个新窗口。而且我在调试中知道代码已执行。

我做错了什么吗?它基于在 Qt Creator 中创建的窗口。我应该工作。

另外:在主窗口中调用新窗口时,它起作用了,代码完全相同。我不明白为什么它在主窗口中不起作用,但在 void 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();

}

主窗口

enter image description here

    #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.");

    }
}

打开新窗口

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

enter image description here

Cpp
#include "createeditmarkdownnoteui.h"
#include "ui_createeditmarkdownnoteui.h"
//#include <QWebEnginePage>

CreateEditMarkdownNoteUi::CreateEditMarkdownNoteUi(QWidget* parent)  : QMainWindow(parent),ui(new Ui::CreateEditMarkdownNoteUi){

    ui->setupUi(this);
}



CreateEditMarkdownNoteUi::~CreateEditMarkdownNoteUi(){
    delete 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 列表(类似于 make 或 qmake,带有要运行/编译的 cpp 文件和 .ui 列表)

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)

输出

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

我已经尝试了另一个堆栈溢出线程中给出的解决方案,但没有用,我不明白为什么(How to open a new window from the main window in Qt?)。

提前感谢您的帮助

最佳答案

问题是对象超出范围。

main 函数中,窗口打开,并且由于事件循环 app.exec(); 而仍然打开。它会阻止到达主函数范围的末尾,直到程序结束并且事件循环返回退出代码。

要在不对代码进行太多更改的情况下解决此问题,您可以使用 new 创建类并摆脱范围问题,为此类设置父级以启用自动删除或设置显式 setAttribute(Qt::WA_DeleteOnClose); 具有相同的目的。

还请记住,如果所有窗口都关闭并且 QApplication::quitOnLastWindowClosed() == true; 整个应用程序将关闭,因此如果需要,请调用 QApplication::setQuitOnLastWindowClosed(false) ; 并使用 QApplication::quit(); 显式退出您的应用程序,例如:

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

关于c++ - Qt打不开新窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45253977/

相关文章:

C++ 在将文本文件读入字符串时如何忽略文本文件中的符号/数字?

qt - QML 如何获取 ListView 中的当前元素索引?

python - Tkinter 将 <Shift-MouseWheel> 绑定(bind)到水平滚动

c++ - 将 Qt Creator 设置为在 Windows 上使用最新版本的 g++ 和 gdb

c++ - WM_EX_TRANSPARENT 不重绘子窗口

html - 使用 HTML 和 CSS 的邮件图标

c++ - 如何更改 Netbeans 7 配置特定的 makefile 宏

c++ - 帮助将 AA 脚本转换为 C++

c++ - 将结构传递给 vector ,打印 vector 会产生奇怪的结果

qt - 如何在 Qt/PyQt/PySide QLabel 中右对齐富文本 (HTML)?