在qprogressbar中显示进度

Display progress in QProgressBar

本文关键字:显示 qprogressbar      更新时间:2023-10-16

我正在使用qprogress显示读取配置文件的状态。我有一个将信号发射到主窗口以显示状态的类。目前,我可以显示状态,但立即显示100%,我希望它更可靠。就像我看到的那样,例如从0到5到5到20到45,依此类推,直到达到100%。到目前为止,我在这里用餐了:

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new 
Ui::MainWindow)
{
    connect(sampleClass, SIGNAL(onDisplayStatus(int)), this, 
    SLOT(onDisplayStatus(int)));
    // OtherClass instance
    // config file has lots of fields to be read
    otherClass->validateConfigfile();
}
MainWindow::onDisplayStatus(int status)
{
    ui->ProgressStatus.setValue(status);
}
SampleClass::displayStatus(int value)
{
    emit onDisplayStatus(value);
}
// This will validate if the config file is valid or existing; the 
// progress will be set to 10 if valid and existing
OtherClass::validateConfigfile() 
{
    // instance of SampleClass
    //10 is the value of progress. 
    //I dont want it to be fixed. Pleas suggest how to properly compute 
    //the value
    sampleClassInstance->displayStatus(10); 
    loadSection1();
    loadSection2();
}
OtherClass::loadSection1()
{
    // load section 1 here
    sampleClassInstance->displayStatus(20);
}
OtherClass::loadSection2()
{
    // load section 2 here
    sampleClassInstance->displayStatus(35);
}

注意:我的配置文件由许多字段组成。以下是一个示例:

[Section 1]
S1Field1 = 0
S1Field2 = 1
S1Field3 = 2
[Section 2]
S2Field1 = 0
S2Field2 = 1
[Section 3]
S3Field1 = 0
S3Field2 = 1
S3Field3 = 2
S3Field4 = 6
S3Field5 = 4
S3Field6 = 9

等等...

我在其他班级中创建了一个方法,该方法将读取每个部分和字段。一旦读取每个部分,直到进度达到100。

,将显示进度值。

请查看文档:https://doc.qt.io/qt-5/qprogressbar.html

您必须设置进度键的最大和最小值。

如果您在主线程中处理(QT GUI的线程),则您的小部件将在完成之前不会更新/重新粉刷,然后直接显示100%。

为了正确使用ProgressBar,您需要在其他过程或某些异步代码中处理一些代码。

ps:您也可以将工作类信号直接连接到progressbar插槽,您不需要MainWindow::onDisplayStatus(int status)

您首先必须在阅读文件时计算进度。从文件中读取输入时,也许最有效地创建进度栏的方法可能会对您有所帮助。

然后,您必须将进度报告给QProgressBar。为此,您的文件读取方法需要接收进度指标作为功能参数,并调用其状态显示方法。如果您不希望明确依赖QT,那么您可能需要创建一个纯抽象的ProgressIndicator接口类,使文件阅读方法使用这样的ProgressIndicator,然后创建一个从ProgressIndicatorQProgressBar继承并连接接口方法的类到QProgressBar中的实现。