Distributing code responsibility
Great, the user can now specify the task name when it's created. What if he makes an error when typing the name? The next logical step is to rename the task after we created it. We'll take a slightly different approach. We want our Task
to be as autonomous as possible. If we attach it to another component (rather than MainWindow
), this renaming feature has to keep working. Thus, this responsibility has to be given to the Task
class:
// In Task.h public slots: void rename(); // In Task.cpp #include <QInputDialog> Task::Task(const QString& name, QWidget *parent) : QWidget(parent), ui(new Ui::Task) { ui->setupUi(this); setName(name); connect(ui->editButton, &QPushButton::clicked, this, &Task::rename); } ... void Task::rename() { bool ok; QString value = QInputDialog::getText(this, tr("Edit task"), tr("Task name"), QLineEdit::Normal, this->name(), &ok); if (ok && !value.isEmpty()) { setName(value); } }
We add a public slot rename()
to connect it to a signal. The body of rename()
reuses what we had previously covered with QInputDialog
. The only difference is the QInputDialog
default value, which is the current task name. When setName(value)
is called, the UI is instantly refreshed with the new value; there's nothing to synchronize or update, the Qt main loop will do its job.
The nice thing is that Task::rename()
is completely autonomous. Nothing has been modified in MainWindow
, so we have effectively zero coupling between our Task
and the parent QWidget
.