Qt Creator / C ++ MySql TableWidget

时间:2014-06-16 20:05:37

标签: c++ mysql qt-creator

我再次遇到一点问题,也许你们可以帮忙!

所以我试图在 tableWidget 中显示数据库查询。

问题是,它不是出现在我在GUI中创建的tableWidget中,而是打开一个只有该查询的全新程序(没有我的其他按钮或标签)。

UI的屏幕截图:http://i57.tinypic.com/206eety.png

相反,它看起来像这样:http://i60.tinypic.com/jkvjuh.png

问题:如何在tableWidget中获取该表?

这是我的 main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QtSql/QSql>
#include <QtGui/QtGui>
#include <QMessageBox>
#include <QtSql/QSqlDatabase>
#include <QTableWidget>
#include <QtSql/QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlQueryModel>

int main(int argc, char *argv[])

{


 QApplication a(argc, argv);
    QTableWidget* tableWidget = new QTableWidget();
    tableWidget->setWindowTitle("Connect to Mysql Database");

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("pizzeria mabo");
    db.setUserName("root");
    db.setPassword("");



 if (!db.open())
    {
        QSqlError err = db.lastError();
        QMessageBox::critical(0, QObject::tr("Database Error"), err.text());
    }




 QSqlQuery query("SELECT * FROM kunden");

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

        int index=0;
        while (query.next())
        {
        tableWidget->setItem(index,0,new QTableWidgetItem(query.value(0).toString()));
        tableWidget->setItem(index,1,new QTableWidgetItem(query.value(1).toString()));
        tableWidget->setItem(index,2,new QTableWidgetItem(query.value(2).toString()));

        tableWidget->setItem(index,3,new QTableWidgetItem(query.value(3).toString()));
        tableWidget->setItem(index,4,new QTableWidgetItem(query.value(4).toString()));
        tableWidget->setItem(index,5,new QTableWidgetItem(query.value(5).toString()));

        tableWidget->setItem(index,6,new QTableWidgetItem(query.value(6).toString()));
        tableWidget->setItem(index,7,new QTableWidgetItem(query.value(7).toString()));
        tableWidget->setItem(index,8,new QTableWidgetItem(query.value(8).toString()));
        index++;
        }


    tableWidget->show();
        return a.exec();


    MainWindow w;
    w.show();

    return a.exec();
}

感谢您的帮助!

0 个答案:

没有答案