我有两个文件:
// main.h
// some code ...
QSqlQuery getCardsQuery;
void readCardsFromDataBase();
void createCard();
//some code
// continue and end of main.h
//main.cpp
void MainWindow::readCardsFromDataBase()
{
myDataBase = QSqlDatabase::addDatabase("QMYSQL", "my_sql_db");
myDataBase.setHostName("localhost");
myDataBase.setDatabaseName("Learn");
myDataBase.setUserName("root");
myDataBase.setPassword("password");
bool ok = myDataBase.open();
qDebug()<< ok;
if (!ok)
QMessageBox::warning(this, "connection Error", "cannot connect to DataBase");
getCardsQuery("select Question, Answer, MainPosition, SecondPosition, IsMustReview\
from Cards", myDataBase); // I got error in here
///error: no match for call to '(QSqlQuery) (const char [106], QSqlDatabase&)'
}
void MainWindow::createCard()
{
getCardsQuery.next();
card = new Card(getCardsQuery.value(0).toString(), getCardsQuery.value(1).toString());
card->setPos(getCardsQuery.value(3).toInt(), getCardsQuery.value(4).toInt());
card->setReviewToday(getCardsQuery.value(4).toBool());
}
初始化getCardsQuery
时出错。我想使用getCardsQuery
global.I想要像这样初始化它:
getCardsQuery("select Question, Answer, MainPosition, SecondPosition, IsMustReview\
from Cards", myDataBase);
如何在头文件中声明它并在main.cpp
文件中全局使用?
答案 0 :(得分:0)
实际上,您可以将getCardsQuery
声明为MainWindow
班级&#39;成员变量。下面的代码大致演示了如何做到这一点:
class MainWindow : public QMainWindow
{
[..]
private:
QSqlQuery *getCardsQuery;
};
在main.cpp
中MainWindow::MainWindow()
: getCardsQuery(0)
{}
void MainWindow::readCardsFromDataBase()
{
[..]
if (!getCardsQuery) {
getCardsQuery = new QSqlQuery("select Question, Answer," \
"MainPosition, SecondPosition," \
"IsMustReview from Cards", myDataBase);
}
[..]
}
void MainWindow::createCard()
{
if (!getCardsQuery) {
getCardsQuery->next();
[..]
}
}