سؤال

I am currently learing Qt, and I am stuck on the problem of using multiple QWidgets and one QMainWindow.

I have setup a project which contains 2 QWidgets and one QMainWindow. This is my idea of using it: design both QWidgets as needed, add them to the mainwindow object, connect the buttons to the correct slots and switch the centerwidget when needed. So I started off with one QMainWindow and then added two QWidgets, including the cpp file, the h file and the ui file. On both QWidgets I added one QPushButton, and called it pushButtonConvert.

Then I went to the cpp file attached to the QMainWindow (mainwindow.cpp) and did the following:

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

Up until this point everything is fine. Now I want to connect the buttons to slots in the mainwindow object, but I can not find the buttons. epochToHuman->pushButtonConvert does not seem to exist, and I can not find any other way to get to the buttons. So am I thinking in a way that is not correct, according to Qt or am I missing something?

Another try at clarifying what I want: I want to use the elements in a QWidget in QMainWindows' cpp file. I want to be able to do things like this:

//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.
هل كانت مفيدة؟

المحلول

You can connect the pushButtonConvert button to MainWindow::convertFromEpochToHuman in the constructor of MainWindow, with:

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

You'll need to make the ui member public first, like you have done for HumanToEpoch.

You should move the declaration of your widgets into MainWindow.h:

// ...
private:
    Ui::MainWindow *ui;

    EpochToHuman * epochToHuman;
    HumanToEpoch * humanToEpoch;
 // ...

and initialise them like this:

epochToHuman = new EpochToHuman(this);
humanToEpoch = new HumanToEpoch(this);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top