7

Qtであるフォームから別のフォームにデータを渡すにはどうすればよいですか?
QWidgetProgect -> QtGuiApplication を作成しました。現在 2 つのフォームがあります。今、あるフォームから別のフォームにデータを渡したいと思っています。

どうすればそれを達成できますか?

ありがとう。

4

2 に答える 2

16

以下に、試してみたいオプションをいくつか示します。

  • 1 つのフォームが別のフォームを所有している場合は、別のフォームでメソッドを作成して呼び出すことができます。
  • Qt のシグナルとスロットメカニズムを使用して、テキスト ボックスを使用してフォームにシグナルを作成し、それを他のフォームで作成したスロットに接続できます (テキスト ボックスtextChangedまたはtextEditedシグナルに接続することもできます) 。

シグナルとスロットの例:

と の 2 つのウィンドウがあるとしFirstFormますSecondFormFirstFormには、QLineEditその UI に という名前のがありmyTextEdit、その UI に という名前の があります。SecondFormQListWidgetmyListWidget

main()また、アプリケーションの機能で両方のウィンドウを作成すると仮定しています。

firstform.h:

class FistForm : public QMainWindow
{

...

private slots:
    void onTextBoxReturnPressed();

signals:
    void newTextEntered(const QString &text);

};

firstform.cpp

// Constructor:
FistForm::FirstForm()
{
    // Connecting the textbox's returnPressed() signal so that
    // we can react to it

    connect(ui->myTextEdit, SIGNAL(returnPressed),
            this, SIGNAL(onTextBoxReturnPressed()));
}

void FirstForm::onTextBoxReturnPressed()
{
    // Emitting a signal with the new text
    emit this->newTextEntered(ui->myTextEdit->text());
}

secondform.h

class SecondForm : public QMainWindow
{

...

public slots:
    void onNewTextEntered(const QString &text);
};

セカンドフォーム.cpp

void SecondForm::onNewTextEntered(const QString &text)
{
    // Adding a new item to the list widget
    ui->myListWidget->addItem(text);
}

main.cpp

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Instantiating the forms
    FirstForm first;
    SecondForm second;

    // Connecting the signal we created in the first form
    // with the slot created in the second form
    QObject::connect(&first, SIGNAL(newTextEntered(const QString&)),
                     &second, SLOT(onNewTextEntered(const QString&)));

    // Showing them
    first.show();
    second.show();

    return app.exec();
}
于 2011-06-01T11:49:11.303 に答える
2

ポインターを使用して、他のフォームから QTextEdit にアクセスすることもできます (それを使用していると仮定します)。

Venemo の例 (FirstForm には QTextEdit があり、SecondForm には QTextEdit にアクセスする必要があるものがあります) から:

firstform.h:

class FistForm : public QMainWindow
{

...

public:
    QTextEdit* textEdit();
};

firstform.cpp:

QTextEdit* FirstForm::textEdit()
{
    return ui->myTextEdit;
}

次に、次のような方法で SecondForm の QTextEdit のテキストにアクセスできます (FirstForm のインスタンスが firstForm と呼ばれると仮定します)。

void SecondForm::processText()
{
    QString text = firstForm->textEdit()->toPlainText();
    // do something with the text
}
于 2011-06-01T16:18:05.770 に答える