我的环境是Qt 4.1,直接使用QString的话,无论界面还是数据库读写都是乱码,终于在网路上面搜索到了解决方法,并编写了例子,可能不完善,大家一起研究吧。源码如下:
#include <QtGui/QApplication>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <QtDebug>
#include <QString>
#include <QTextCodec>
#include <QListWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextCodec::setCodecForCStrings(QTextCodec::codecForLocale());
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("e:\\db.db");
if (!db.open()) {
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection.\n"
"This example needs SQLite support. Please read "
"the Qt SQL driver documentation for information how "
"to build it.\n\n"
"Click Cancel to exit."), QMessageBox::Cancel,
QMessageBox::NoButton);
return false;
}
QSqlQuery rs(db);
rs.exec("create table person(name text,age integer)");
rs.exec("delete from person where age=119");
QString strSql("insert into person(name,age) values('中国是在亚洲',119)");
rs.exec(strSql);
bool blnOpen=rs.exec("select * from person");
if (blnOpen==false)
{
qDebug("Query database error\n");
return -1;
}
QListWidget *window=new QListWidget();
while (rs.next()) {
int age= rs.value(1).toInt();
QString name=rs.value(0).toString();
window->addItem(name);
}
QString test="这是测试窗体";
qDebug("字符串的长度是:%d",test.length());
window->setWindowTitle(test);
window->show();
return a.exec();
}
[ 此贴被XChinux在2006-07-02 20:41重新编辑 ]