gpt4 book ai didi

c++ - 使用插槽创建对话框

转载 作者:行者123 更新时间:2023-11-30 03:14:56 25 4
gpt4 key购买 nike

单击按钮时,我需要在当前程序之上创建一个新窗口(在本例中我尝试创建一个对话框)。我有这个工作,但我无法编辑对话框的内容。据我所知,没有为此创建 .ui 文件,它仅在我将按钮连接到函数时创建。

我曾尝试使用 QMessageBox,但无法根据需要调整窗口大小。并且仍然遇到了添加其他元素的问题。

void MyNameSpace::openInfoDialog()
{
QDialog* Dialog = new QDialog(this);
Dialog->setWindowTitle("View Stuff");
Dialog->setMinimumSize(500,250);
Dialog->adjustSize();
DialogRunner* msgRunner = new DialogRunner(Dialog, this);
msgRunner->safeExec();
}

这是我的连接

connect(_Widget.InfoBtn, SIGNAL(clicked(bool)), this, SLOT(openInfoDialog()));

此代码确实会在单击时生成一个对话框,但我需要能够向其中添加标签等内容。我还使用 QT Designer 作为我的所见即所得。

我该怎么做才能通过单击按钮创建新窗口并在其中填充其他文本等?

最佳答案

I have this working, but I am having trouble editing the content of the Dialog

你可以在你的项目中添加ui文件: enter image description here

使用该选项,Qt Creator 将创建一个包含 cpp 和 h 文件以及一个 ui 文件的类,您可以在其中添加您习惯的其他小部件。使用导入指令在您需要的地方使用您的类,就像您在上面的代码中所做的那样,您将拥有可用的 ui 文件。然后将按钮的点击信号与对话框类的插槽连接起来。您可以在包含按钮的类的构造函数中执行此操作。

您可以在书 C++ GUI Programmingwith Qt 4 中更详细地阅读这种方法第 2 章:创建对话框。它可以在网上免费获得。它使用 Qt4,但在 Qt5 中它的工作方式相同。

编辑:这是一个最小的示例,向您展示了您可以在哪里使用所需的部分:一个带有按钮的主窗口(在 ui 文件中)。一个 Dialog 类,它也有一个 ui 文件(上面有几个小部件)。单击主窗口上的按钮时,将显示对话框。 Thjs 是我之前问过你的。它使交流/测试更容易。

专业文件

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app

SOURCES += \
dialog1.cpp \
main.cpp \
mainwindow.cpp

HEADERS += \
dialog1.h \
mainwindow.h

FORMS += \
dialog1.ui \
mainwindow.ui
**main.cpp**

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}

主窗口.h

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();

private:
Ui::MainWindow *ui;
};

**mainwindow.cpp**
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialog1.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
Dialog1* dialog = new Dialog1(this);
connect( ui->pushButton_1, SIGNAL(clicked()), dialog, SLOT(show()));
}

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

对话框1.h

namespace Ui {
class Dialog1;
}

class Dialog1 : public QDialog
{
Q_OBJECT

public:
explicit Dialog1(QWidget *parent = nullptr);
~Dialog1();

private:
Ui::Dialog1 *ui;
};
#endif // DIALOG1_H

dialog1.cpp

#include "dialog1.h"
#include "ui_dialog1.h"

Dialog1::Dialog1(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog1)
{
ui->setupUi(this);
}

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

关于c++ - 使用插槽创建对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com