2015-10-07 77 views
1

我有一個MainWindow帶有一個菜單,打開一個註冊對話框。如何在註冊後更新MainWindow中的tableView?更新主窗口對話框

這裏是我的MainWindow實現:

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


void MainWindow::list() 
{ 
    qDebug() << "test"; 
    QSqlQueryModel *model = new QSqlQueryModel(); 
    //model->clear(); 
    model->setQuery("SELECT test_qt FROM db_qt WHERE strftime('%Y-%m-%d', date)='"+dateTime.toString("yyyy-MM-dd")+"'"); 
    model->setHeaderData(0, Qt::Horizontal, tr("qt_test")); 
    ui->tableView->setModel(model); 
} 

void MainWindow::on_actionMenu_triggered() 
{ 
    dialog_test->show(); 
} 

這裏是我的對話實現

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

void Dialog_test::insert_date(){ 
    QSqlQuery qry; 
    qry.prepare("INSERT INTO db_qt(test_qt) VALUES (?)"); 
    qry.addBindValue(id); 
    if (qry.lastInsertId()>0){ 
     QMessageBox::information(this,"test", "Success"); 
     MainWindow *mw = new MainWindow(this); 
     mw->list(); // I call back list, but not update the tableView the MainWindow. 
    } 
} 

回答

2

在你的代碼

MainWindow *mw = new MainWindow(this); 

以下行創建了一個主窗口更新它的列表。我認爲這確實發生了,但窗口從未顯示,因此您沒有看到任何內容。你真正想要做的是更新你的現有主窗口的列表。

基本上有兩種方法可以做到這一點。你可以獲得一個指向現有主窗口的指針(它可以提供給對話框的構造函數或它自己的方法)或者使用Qt的概念,這是我認爲的方式。

  1. 首先,在對話框的標題定義信號:在你的函數

    ... 
    signals: 
        void user_registered(); 
    ... 
    
  2. 然後你發出信號

    //MainWindow *mw = new MainWindow(this); 
    //mw->list(); 
    emit this->user_registered(); 
    
  3. 確保list()方法在MainWindow標頭中聲明爲SLOT

  4. 連接信號在主窗口的構造函數調用list()插槽:

    ... 
    QObject::connect(this->dialog_test, SIGNAL(user_registered()), this, SLOT(list())); 
    ... 
    

通過這種方法,對話框不需要知道主窗口的。它基本上只是告訴任何有興趣註冊用戶並且主窗口自行完成操作的用戶。

+0

謝謝,現在它工作。 :) – user628298