c++ - Qt SQL 数据库自动完成

标签 c++ sql qt sqlite autocomplete

我正在尝试使用 SQLite 数据库中的值创建自动完成 lineEdit。问题是 lineEdit 中没有自动完成功能。我使用的代码如下:

AutoComplete();
QCompleter *Account_completer = new QCompleter(AccountList);
QCompleter *Product_completer = new QCompleter(ProductList);
Account_completer->setCaseSensitivity(Qt::CaseInsensitive);
Product_completer->setCaseSensitivity(Qt::CaseInsensitive);
ui->lineEdit_Invoice_Account->setCompleter(Account_completer);
ui->lineEdit_Invoice_Product->setCompleter(Product_completer);

我的自动完成程序如下:

QSqlQuery Account;
QSqlQuery Product;
switch(ui->comboBox_Invoice_Account_Search->currentIndex())
{
    case 0:
        Account.prepare("SELECT Customer_ID FROM Customer");
        Account.exec();
        break;
    case 1:
        Account.prepare("SELECT Company_Name FROM Customer");
        break;
    case 2:
        Account.prepare("SELECT Company_Owner FROM Customer");
        break;
    case 3:
        Account.prepare("SELECT Phone_Number FROM Customer");
        break;
    case 4:
        Account.prepare("SELECT BULSTAT FROM Customer");
        break;
}
switch(ui->comboBox_Invoice_Product_Search->currentIndex())
{
    case 0:
        Product.prepare("SELECT Product_CODE FROM Product");
        break;
    case 1:
        Product.prepare("SELECT Product_Name FROM Product");
        break;
}
Account.exec();
qDebug() << "SQL QUERY Account:" << Account.executedQuery();
qDebug() << "SQL ERROR Account:" << Account.lastError();
while(Account.next())
    AccountList = Account.value(0).toStringList();
Product.exec();
qDebug() << "SQL QUERY Product:" << Product.executedQuery();
qDebug() << "SQL ERROR Product:" << Product.lastError();
while(Product.next())
    ProductList = Product.value(0).toStringList();
for(int x = 0; x <= Account.size(); x++)
    qDebug() << AccountList.at(x).toLocal8Bit().constData() << endl;
for(int y = 0; y <= Product.size(); y++)
    qDebug() <<  ProductList.at(y).toLocal8Bit().constData() << endl;
}

最佳答案

我不知道您是否已正确初始化数据库连接和QSqlQuery。但不需要手动填充QCompleter。您可以使用像 QSqlTableModel 这样的模型,并使用 QCompleter::setCompletionColumn 来设置完成者要搜索的特定列:

QSqlTableModel * model = new QSqlTableModel(this,db);
model->setTable( "Customer" );
model->select();

QCompleter *Account_completer = new QCompleter(model, this);
completer->setCompletionColumn(someIndex);

您可以自己定义列索引someIndex,可能在这里通过组合框的选定索引来定义。

关于c++ - Qt SQL 数据库自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663061/

相关文章:

c++ - atlsafe.h 中奇怪的 C++ 运算符语法

c++ - 构建 NFIQ2 时从 ‘char’ 到 ‘char*’ 的无效转换

python - 如何在 python 的原始 SQL 中提交更新

c++ - Qt 为某些应用程序数据指定位置

python - 无法导入 PyQt4.QtGui

c++ - 为什么 ostream::operator<< 是 char 参数的全局函数?

c++ - 可疑的指针到指针转换(区域太小)

sql - 遇到 SQL 错误 : ORA-01843: not a valid month

MySQL 数据传输/更新到另一个数据库

c++ - 如何轻松地展开一排 Qt 小部件,使它们始终均匀分布?