1. 程式人生 > >Qt父子視窗互換資訊

Qt父子視窗互換資訊

1.建立父子窗體
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QDialog * d= new QDialog(this);
    //d->show(); 
    d->exec();
}

MainWindow::~MainWindow()
{
    delete ui;
}
2.建立選單視窗
要用到.ui選單檔案,建立子選單,然後進行“轉到槽”的操作
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QDialog * d= new QDialog(this);
    //d->show();
   // d->exec();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_action456_triggered()
{
    QDialog * d= new QDialog(this);
    d->show();
}
3.父子視窗傳遞資訊
//mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    void putText(QString s);



private slots:
    void on_action456_triggered();

    void on_label_linkActivated(const QString &link);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

//dialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H

#include <QDialog>

namespace Ui {
class MyDialog;
}

class MyDialog : public QDialog
{
    Q_OBJECT


public:
    explicit MyDialog(QWidget *parent = 0);
    ~MyDialog();
signals:
    void giveText(QString s);
private slots:
        void on_pushButton_clicked();

        void on_lineEdit_cursorPositionChanged(int arg1, int arg2);

private:
    Ui::MyDialog *ui;
};

#endif // MYDIALOG_H

//mainwindow.cpp
#include <QDialog>
#include "mydialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QDialog * d = new QDialog(this);
    //d->show();
   // d->exec();
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::putText(QString s)
{
    ui->label->setText(s);
}


void MainWindow::on_action456_triggered()
{
    QDialog * d= new MyDialog(this);
    connect(d,&MyDialog::giveText,this,&MainWindow::putText);
    d->show();
}

//dialog.cpp
#include "mydialog.h"
#include "ui_mydialog.h"

MyDialog::MyDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MyDialog)
{
    ui->setupUi(this);
}

MyDialog::~MyDialog()
{
    delete ui;
}

void MyDialog::on_pushButton_clicked()
{
    QString s = ui->lineEdit->text();
    emit giveText(s);
}