【问题标题】:How to block for loop till sqlite query get executed?如何阻止for循环直到sqlite查询被执行?
【发布时间】:2014-02-08 14:40:09
【问题描述】:

我正在用 Qt 编写程序,下面是我的代码的一部分:

for(int row=0; row < 15; row++)
    {
        for(int column=0; column < 12; column++ )
        {
            if(query->exec(db->getInsertQuery(row,column)))
            {

            }else
                qDebug() << "Failed to insert cell";
        }
    }

当我运行这个程序时,它进入“无响应”状态。当我跑步时

    query->exec(db->getInsertQuery(0,0));
    query->exec(db->getInsertQuery(0,1));
    ....

代替 for 循环程序运行正常,但我不能在我的程序中写这么多行。您能否建议我在执行查询之前阻止 for 循环的方法以及如何在某些框中显示进度条直到 for 循环完成?

【问题讨论】:

  • 您可以使用QProgressDialog在许多同步操作中显示进度条并避免无响应状态。有关示例,请参见文档页面。
  • 关键是你必须回到事件循环。模态QProgressDialog 将为您调用processEvents()(请参阅其文档);否则你需要以某种方式允许事件处理。另请参阅this
  • @peppe 我通过将 query->finish() 放在 if-else 下面解决了这个问题,我的程序运行良好:)

标签: c++ qt sqlite qt4


【解决方案1】:

如果您使用的是 QtSql,我假设您应该使用 execBatch() 方法来完成此类任务

Example

QSqlQuery q;
q.prepare("insert into myTable values (?, ?)");

QVariantList ints;
ints << 1 << 2 << 3 << 4;
q.addBindValue(ints);

QVariantList names;
names << "Harald" << "Boris" << "Trond" << QVariant(QVariant::String);
q.addBindValue(names);

if (!q.execBatch())
    qDebug() << q.lastError();

【讨论】:

    【解决方案2】:

    您应该循环执行您的查询并使用 QProgressDialog 和 qApp->processEvents() 调用的组合。

    基本上你会做以下事情:

    // Run queries with numbers 0-99
    for ( int i = 0; i < 100; i++ )
    {
         // run your query
    
         // update the progress dialog value
    
         // Run the Qt event loop to handle the GUI updates and avoid the "not responsing" app state
         qApp->processEvents( QEventLoop::ExcludeUserInputEvents );
    }
    

    你可以看看我的视频生成器类:https://sourceforge.net/p/karlyriceditor/code/HEAD/tree/src/videogenerator.cpp - 检查 generate() 函数,它与你需要的非常相似,生成视频文件并在执行此操作时更新进度对话框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      相关资源
      最近更新 更多