2013-02-12 77 views
0

我想在Qt GUI中用單選按鈕來顯示一些數據庫行值。這可以如何實現?這可以使用foreach循環來完成,我猜。我已經研究了一下以下類:在Qt中用單選按鈕顯示數據庫值?

1)QMainWindow 2)QSqlTableModel 3)QTableWidget。

但是哪一個滿足我的要求?我無法執行它,請指導我。提前致謝。

我已經在我的源高達該實施文件 -

main.cpp中

#include <QtGui/QApplication> 
#include <QtSql> 
#include <QTableWidget> 
#include <QMessageBox> 
#include "mainwindow.h" 
#include <QRadioButton> 
#include <QVBoxLayout> 
#include <QGroupBox> 

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

    QTableWidget* table = new QTableWidget(); 
    table->setWindowTitle("Connect to Mysql Database Example"); 

     QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); 
     db.setHostName("localhost"); 
     db.setDatabaseName("guests"); 
     db.setUserName("sri"); 
     db.setPassword("******"); 
     if (!db.open()) 
     { 
      QMessageBox::critical(0, QObject::tr("Database Error"), 
      db.lastError().text()); 
     } 

     QSqlQuery query("SELECT * FROM new_members"); 

     table->setColumnCount(query.record().count()); 
     table->setRowCount(query.size()); 

     int index=0; 
     while (query.next()) 
     { 

      table->setItem(index,0,new QTableWidgetItem(query.value(0).toString())); 
      table->setItem(index,1,new QTableWidgetItem(query.value(1).toString())); 

      index++; 

     } 

// This is sample radiobutton from QGroupBox class. Like this I need to implement the values from DB in with radio button selections for each value 

     QMainWindow *window = new QMainWindow(); 
     window->setWindowTitle(QString::fromUtf8("QGroupBox")); 
     window->resize(400, 400); 
     QGroupBox *groupBox = new QGroupBox("Radio Buttons"); 
     QRadioButton *radio1 = new QRadioButton("Radio button 1"); 
     radio1->setChecked(true); 
     QVBoxLayout *vbox = new QVBoxLayout; 
     vbox->addWidget(radio1); 
     groupBox->setLayout(vbox); 
     window->setCentralWidget(groupBox); 
     window->show(); 

     table->show(); 
             //MainWindow w; w.show(); 

     return a.exec(); 
} 

回答

1

使用QSqlTableModel驅動QTableView,你將需要自定義QStyledItemDelegateQRadioButtonyes I said draw, and not create),並創建一個編輯器小部件(當然這真的會是一個QRadioButton)。

這是一個相當大的工作,所以你需要閱讀上面的類文檔來重新實現你需要的位。從MVC documents開始。

+0

非常感謝您的回答,因爲我是Qt新手,請向我解釋一步一步的程序(還簡化了)以完成我的任務... :) – highlander141 2013-02-12 14:07:25

+1

如果您是Qt的新手,那麼你需要學習,而且你不會從一步一步的指南中學習任何東西(更不用說你正在做的事情不是微不足道的)。閱讀MVC文檔,然後創建一個程序,該程序可以將現有的SQL數據庫加載到'QSqlTableModel'中,在完成這些之後,您將遇到特定的問題,您可以在此網站上發佈新問題。 – cmannett85 2013-02-12 14:12:13