Elmo Huitz
Elmo Huitz

Reputation: 29

How to access ui from main window in another qdialog?

I am having trouble accessing a QTextEdit from a main window in another form. Please help.

void properties::on_okWordPushButton_clicked()
{
    if (ui->wordcombo->currentText() == "All Words") {

        int wordCount = notepad->textEdit->toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count();
        ui->wordcountlabel->setText(QString::number(wordCount));

    }
}

I am getting an error since I cannot read notepad->textEdit

Upvotes: 1

Views: 351

Answers (2)

Tvord
Tvord

Reputation: 33

You can use at least 2 possibilities:

  1. Dirty way: On form creation, pass pointer to your QTextEdit:
// mainwindow.cpp
auto myProperties = new properties(notepad->textEdit);
...

// properties.h
QTextEdit *outerEditor;

// properties.cpp
properties::properties(QTextEdit *editor) {
 outerEditor = editor;
 ...
}

Then, on your slot you can use:

int wordCount = editor->toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count();
  1. Qt-way: Remember - signals/slots are awesome.

Just after form creation, you can connect signal from MainWindow to properties passing text in your QTextEdit and store it locally:

// MainWindow.cpp
auto myProperties = new properties(notepad->textEdit);
connect(this->textEdit, QOverload<QString>::of(&QTextEdit::valueChanged), myProperties, GetNewValue);

// properties.h
void GetNewValue(QString val);

// properties.cpp
void properties::GetNewValue(QString val) {
    ui->wordcountlabel->setText(QString::number(val.toPlainText().split(QRegExp("(\\s|\\n|\\r)+"), QString::SkipEmptyParts).count());
}

Upvotes: 1

F.Guerinoni
F.Guerinoni

Reputation: 277

You can't do this, the ui is a private member of a widget, create a function that returns or sets what you need!

Upvotes: 0

Related Questions