I'm starting to program in Qt and am looking for best practices on where in the code to write the connect
statements so that the code is more readable.
From the current perspective, it seems that defining connect
on arbitrary locations (provided that the arbitrary locations don't mean a functional difference) can lead to very hard code to read.
Currently, I find the most intuitive way to define the connect
statements in the constructor of the class that contains the SLOTS.
Is there a standard or a recommended best practice?
I like to have a function for each "main" part of my layout for initialization. Below is an example of a constructor. Each of the create
functions returns a group box widget.
MissionConfiguration::MissionConfiguration(QWidget* parent) : QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(createMissionConfigurationGroupBox());
layout->addWidget(createNetAcquireGroupBox());
layout->addWidget(createSystemStatus());
layout->addWidget(createStatusButtons());
setLayout(layout);
}
In each of these "create" functions, the appropriate signals/slots are connected. It helps me keep things organized if the widget is complicated.
Here is an example of the createStatusButtons
function:
QGroupBox* MissionConfiguration::createStatusButtons() {
// on the qbutton status
QGroupBox *runModes = new QGroupBox(tr("Run Modes"));
QHBoxLayout *runModeLayout = new QHBoxLayout;
live = new QRadioButton(tr("Live"));
playback = new QRadioButton(tr("Playback"));
simulation = new QRadioButton(tr("Simulation"));
QPushButton *logout = new QPushButton("Logout");
simulation->setChecked(true);
connect(recorder, SIGNAL(isConnected(bool)), live, SLOT(setEnabled(bool)));
connect(recorder, SIGNAL(isConnected(bool)), playback, SLOT(setEnabled(bool)));
connect(logout, SIGNAL(clicked()), this, SLOT(logout()));
runModeLayout->addWidget(live);
runModeLayout->addWidget(playback);
runModeLayout->addWidget(simulation);
runModeLayout->addWidget(logout);
runModes->setLayout(runModeLayout);
return runModes;
}
Really, the "best" way to do is is how you like it and what is easy for you to remember. I recommend coming up with an idiom that you can understand, so in the future if you have to edit your code, you'll know exactly where to look.