c++ - 如何将 Qt 代码分解成单独的部分?

标签 c++ qt

所以我目前正在编写一个 Qt 应用程序,但对它还很陌生,不确定某些东西应该如何设计。随着我添加越来越多的代码,我的 MainWindow.cpp 变得越来越大而且难以控制。我很好奇将我的代码分成较小文件的正确方法是什么。我希望移动到单独文件的每个组件都会对 UI 进行更改。我目前正在做的只是创建一个新的 .cpp 文件,然后包括我的 MainWindow 和 MainWindow ui。这是我放在自己文件中的函数示例。

#include <QDebug>
#include <QString>
#include <QPalette>
#include "master_main_window.h"
#include "ui_master_main_window.h"
#include "cmd_net.h"
#include "cmd.h"


/*
 * Send a command/data packet to the host
 */
void MasterMainWindow::sendCommand() {

    // Disable some GUI components
    ui->con_btn_cmd_disc->setEnabled(false);
    ui->con_btn_cmd_rec->setEnabled(false);
    ui->cmd_edit->setEnabled(false);
    ui->cmd_btn_send->setEnabled(false);

    // Send the packet through the open socket
    sendCmdPacket(ui->cmd_edit->text().toLocal8Bit().data(), cmdSocket);

    // Enable the socket notifier
    cmdSockNotifier->setEnabled(true);

    qDebug() << "Command sent:"
             << (ui->cmd_edit->text().toLocal8Bit().data())
             << "\nSent Packet";
}

如您所见,我只是包含了“master_main_window.h”和“ui_master_main_window.h”,它们使我可以访问 MainWindow 类中可用的所有不同函数/变量/ui。 我很好奇我这样做的方式是否正确,或者是否有更好的方法来实现我将函数分离到单独文件中的目标。

最佳答案

如果我得到你所问的正确,因为你在这里使用指针,你可以简单地在不同的文件中编写其他类,并将 ui 中的变量传递给它们。 例如,假设您的 ui 中包含以下变量:

QWidget * leftWidget;
QWidget * centerWidget;
QWidget * rightWidget;

您可以编写继承QWidget 的类并将这些变量赋予它们,如下所示:

class leftWidgetClass : public QWidget
{
  //your code here
}

等等... 然后在 MainWindow 的构造函数中,您可以这样做:

leftWidget = new leftWidgetClass();
rightWidget = new rightWidgetClass();
centerWidget = new centerWidgetClass();

关于c++ - 如何将 Qt 代码分解成单独的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19761038/

相关文章:

c++ - 如何使 QCheckBox 只读,但不灰显

c++ - 在C++中查找角度的正弦和余弦值

c++ - 将 QWidget 嵌入到 X11 窗口中

c++ - 将新项目添加到基于 QAbstractListModel 的模型时,QML View 不会更新

python - 主窗口小部件调整大小(Pyside)

c++ - 每次要引入新功能时都要避免使用新类?

c++ - 无法使用 QtCreator #include <QWebView>

c++ - 遍历链表C++并返回用户输入的最高值

c++ - 在 htmlcxx 中查找 'strings.h' 时出错

c++ - 从 c 函数在 qtextedit 上显示消息