I want to create a window application with Qt framework and C , in which an object is created to operate hardware, and should be accessible to MainWindow and all its members and methods. I do not have very much experience of doing things like this.
int main(int argc, char *argv[]) {
QApplication qApp(argc, argv);
CoolHardware *CoolHardware500 = new CoolHardware; // Object that connects to hardware.
CoolHardware500.Connect();
// Show main window here.
MainWindow qApp_Win(CoolHardware500); // This is the only elegant way I could think.
qApp_Win.show();
return qApp.exec();
// Deconstructor.
CoolHardware500>~CoolHardware();
}
In the methods of MainWindow, is not accessible. How to solve this?
void MainWindow::CoolHardwareDoSomething() {
CoolHardware500->DoSomehing(); // Here CoolHardware500 is shown as not defined.
}
Questions:
- Is it an elegant way to create an hardware-operating object in the main() function? How to make it accessible to the members/methods of the MainWindow?
- Is it better to create objects in the constructor of the MainWindow and deconstruct objects in the MainWindow deconstructor? In this way, accessing object is easy.
- If this two ways are both not elegant ways of doing things, what is the elegant way of doing that?
Thank you very much.
CodePudding user response:
MainWindow
is subclassing QMainWindow, but it's a regular C class, so just store either an instance directly, or a pointer, as a member variable on it.
In MainWindow.h (or .hpp):
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
// Either this:
CoolHardware500* m_coolHardwarePtr;
// Or that:
CoolHardware500 m_coolHardware;
};
In the constuctor MainWindow::MainWindow
you can pass arguments to the CoolHardware500
ctor as needed, or use a new
if you use a pointer.
If using a pointer, you also want to have the destructor MainWindow::~MainWindow
do a delete m_coolHardwarePtr;
.
You could also use a smart pointer (like std::unique_ptr
) to avoid to remember to do that delete yourself.
Mainwindow.cpp, assuming you have a Ctor CoolHardware500::CoolHardware500(int)
:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow),
m_coolHardware(1),
m_coolHardwarePtr(new CoolHardware500(1))
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
delete m_coolHardwarePtr;
}
CodePudding user response:
Here's how:
struct MainWindow : QMainWindow {
private:
CoolHardware hardware;
// ...
public:
MainWindow() {
hardware.connect();
// ...
}
// use `hardware`
};