Question

I am building a notepad and want to count the words in a dialog.

QString input = ui->textEdit->toPlainText();
int spaces = input.count(" ");
ui->NumWordsLabel->setNum(spaces);

This is my attempt so far.

However, I want to execute this code in my dialog so I need to pass the

ui->textEdit->toPlainText()

Into my dialog.

This is how I create my dialog...

void MainWindow::on_actionWord_Count_triggered()
{
    word_count = new Word_count();
    word_count->show();
}

How would I get the required information into the dialog?

Thanks.

Was it helpful?

Solution

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:

  1. 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.
  2. 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.
  3. Pass the parent parameter to your inheriting class, whether that be QDialog, QWidget or QObject, using the constructor initializer list syntax. This is done in the source file example with : QDialog(parent).
  4. You can add as many arguments as you need, but they should be before the parent argument. This is because the parent 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.
  5. 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 of show so that users must close your word count dialog before continuing with their work.

OTHER TIPS

Add a slot like void setText( const QString& text ) to your Word_count class.

Then, you can emit a signal like void textChanged( const QString& text ) const from your MainWindowclass.

Don't forget to connect both.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top