多个 QWidets 到一个 QMainWindow 中

Multiple QWidets into one QMainWindow

本文关键字:一个 QMainWindow QWidets 多个      更新时间:2023-10-16

我目前正在研究Qt,我被困在使用多个QWidgets和一个QMainWindow的问题上。

我已经设置了一个包含2个QWidgets和一个QMainWindow的项目。这是我使用它的想法:根据需要设计两个QWidgets,将它们添加到主窗口对象,将按钮连接到正确的插槽,并在需要时切换中心小部件。所以我从一个QMainWindow开始,然后添加两个QWidgets,包括cpp文件,h文件和ui文件。在两个QWidgets上,我都添加了一个QPushButton,并称之为pushButtonConvert。

然后我转到附加到QMainWindow(主窗口.cpp)的cpp文件并执行以下操作:

EpochToHuman * epochToHuman = new EpochToHuman();
HumanToEpoch * humanToEpoch = new HumanToEpoch();

到目前为止,一切都很好。现在我想将按钮连接到主窗口对象中的插槽,但找不到按钮。epochToHuman->pushButtonConvert似乎不存在,我找不到任何其他方法来访问按钮。那么,根据Qt,我的想法是不正确的,还是我错过了什么?

另一个尝试澄清我想要什么:我想在QMainWindows的cpp文件中使用QWidget中的元素。我希望能够做这样的事情:

//In object MainWindow.cpp
QWidget * a = new QWidget
//Let's say a is a custom widget with a label in it. This label is called Label
a->Label->setText("Hello, World!");
//This gives an error because a does not have a member called Label
//How can I change the text on the label of a?
//And I think if I will be able to change the text of this label, I will also be able to dance around with buttons as needed.

您可以将pushButtonConvert按钮连接到 MainWindow 的构造函数中的MainWindow::convertFromEpochToHuman,使用:

connect(epochToHuman->ui->pushButtonConvert, SIGNAL(clicked(bool)), this, SLOT(convertFromEpochToHuman()));

您需要先公开ui成员,就像您为HumanToEpoch所做的那样。

您应该将小部件的声明移动到MainWindow.h

// ...
private:
    Ui::MainWindow *ui;
    EpochToHuman * epochToHuman;
    HumanToEpoch * humanToEpoch;
 // ...

并像这样初始化它们:

epochToHuman = new EpochToHuman(this);
humanToEpoch = new HumanToEpoch(this);