0

我将首先解释我的主要目标。我有一个主窗口,上面有 7 个按钮(除其他外),当您点击每个按钮时,它会关闭当前窗口并打开一个新窗口。所有窗口都有相同的 7 个按钮,因此您可以在每个窗口之间切换。由于所有窗口都有完全相同的 7 个按钮,我想设置一个函数,每个类都可以调用该函数来设置每个按钮并连接到我的 mainwindow.cpp 中的 slot()(在下面的示例中称为 setupSubsystemButtons)。但是,我似乎无法使用标准“this->close()”关闭窗口......当我从主窗口转到另一个窗口(主窗口关闭)但当我从不同的窗口说主窗口,不同的窗口不会关闭。建议将不胜感激。

mainwindow.cpp(相关部分)

void MainWindow::ECSgeneralScreen()
{
    ECSgeneralCommand *ECSgeneral = new ECSgeneralCommand;
    this->close();
    ECSgeneral->show();
    //opens up the ECS screen
}

void MainWindow::homeScreen()
{
    MainWindow *home = new MainWindow;
    this->close();
    home->show();
    //opens up the ECS screen
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupSubsystemButtons(QGridLayout *layout)
{
    //Push Button Layout
    homeScreenButton = new QPushButton("Home");
    layout->addWidget(homeScreenButton, 3, 11);
    connect(homeScreenButton, SIGNAL(clicked()), this, SLOT(homeScreen()));

    ECSgeneralScreenButton = new QPushButton("General");
    layout->addWidget(ECSgeneralScreenButton,5,11);
    connect(ECSgeneralScreenButton, SIGNAL(clicked()), this, SLOT(ECSgeneralScreen()));
}

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtWidgets>
#include <QDialog>


namespace Ui {
class MainWindow;
}

class MainWindow : public QDialog
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    QWidget *window;
    void setupSubsystemButtons(QGridLayout *layout);
    ~MainWindow();
private slots:

public slots:
    void ECSgeneralScreen();
    void homeScreen();

};

#endif // MAINWINDOW_H

ecs 通用命令窗口

include "ecsgeneralcommand.h"
#include "mainwindow.h"

#include <QtWidgets>
#include <QtCore>

ECSgeneralCommand::ECSgeneralCommand(MainWindow *parent) :   QDialog(parent)
{
    QGridLayout *layout = new QGridLayout;
    QWidget::setFixedHeight(600);
    QWidget::setFixedWidth(650);

    ...


    //Setup Subsystem Buttons
    test.setupSubsystemButtons(layout);

    setLayout(layout);
}

ecsgeneralcommandWindow 标头

#ifndef ECSGENERALCOMMAND_H
#define ECSGENERALCOMMAND_H

#include <QDialog>
#include <QMainWindow>
#include <QtWidgets>
#include <QObject>
#include "mainwindow.h"

class ECSgeneralCommand : public QDialog
{
Q_OBJECT

public:
    explicit ECSgeneralCommand(MainWindow *parent = 0);

private:
    MainWindow test;
public slots:

};

#endif // ECSGENERALCOMMAND_H
4

1 回答 1

1

插槽只是正常的功能。当 Qt 调用一个槽时,它最终会调用适当的接收器方法。换句话说,this等于connect语句的第三个参数的值。你通过了this那里,所以接收者是 MainWindow 对象。例如MainWindow::homeScreen方法总是试图关闭MainWindow。如果它已经隐藏,则此操作无效。

您应该在每个窗口类中都有一个插槽并将按钮连接到适当的接收器,或者使用指向当前活动窗口的指针而不是this在调用close(). 但首先你的架构很奇怪。为什么需要为每个窗口创建这些按钮?创建一次并在所有窗口中使用是合理的。也不需要隐藏和显示窗口。您可以创建一个带有按钮的主窗口和一个QStackedWidget包含所有其他窗口内容的主窗口。也许您甚至可以使用QTabWidget这些按钮来代替。

于 2013-12-10T23:15:14.897 回答