Generally you can pass constructor arguments to pass data to your classes. For example:
Header file:
class Word_count : public QDialog
{
Q_OBJECT
public:
explicit Word_count(QString text, QObject *parent = 0);
...
}
Source file:
Word_count(QString text, QObject *parent)
: QDialog(parent)
{
ui->setup(this);
... figure out word count and set labels ...
}
How to use:
void MainWindow::on_actionWord_Count_triggered()
{
word_count = new Word_count(ui->textEdit->toPlainText());
word_count->show();
}
Important notes:
- The
QObject *parent
argument should always be present in the constructor arguments. Make sure to only place the= 0
in the header file, or else you will get an error. - Your constructor should be marked explicit, unless you know you do not want that. Explicit prevents the C++ compiler from automatically casting to your type using a given constructor.
- Pass the parent parameter to your inheriting class, whether that be
QDialog
,QWidget
orQObject
, using the constructor initializer list syntax. This is done in the source file example with: QDialog(parent)
. - You can add as many arguments as you need, but they should be before the
parent
argument. This is because theparent
argument has a default value that can be implied. Because you must specify arguments in order, it can not be implied if there are required parameters after it. - This only will work for creating the dialog. If you want the dialog to dynamically update, you'll need to use a slot or method like suggested by others. Alternatively, if you don't want a dynamically updating dialog, consider using
exec
instead ofshow
so that users must close your word count dialog before continuing with their work.