我有一个耗时的计算,该计算取决于double值。为此,我创建了一个GUI,可以在其中使用 QDoubleSpinBox
设置计算值。双旋转盒 QDoubleSpinBox::valueChanged(double)
信号连接到插槽,该插槽使用 QtConcurrent::run
在新线程中开始繁重的计算。问题是,当我添加进度条时,出现进度条时,双旋转框会自动填充其内容(零填充,直到小数位数为止)。我的感觉是,这是因为双旋转框失去了焦点(即进度条是选定的小部件)。
我的问题是:
不能用零填充其余的小数?
This video显示了如何在不显示进度条时继续编辑双旋转框,而在显示进度条时,双旋转框用零填充其精度。这是当前的行为,而不是所需的行为。理想的情况是计算完成后,双旋转框没有自动用零填充其空的小数位。这是用于视频的代码(在GitHub中完全可用):
header
class DoubleSpinboxHeavyComputation : public QWidget
{
Q_OBJECT
public:
explicit DoubleSpinboxHeavyComputation(QWidget *parent = nullptr);
~DoubleSpinboxHeavyComputation();
signals:
void computationDone();
void progressSignal(int progress_state);
private slots:
void startHeavyComputationInThread();
void heavyComputation();
private:
Ui::DoubleSpinboxHeavyComputation *ui;
int n_ = 0;
};
实现
DoubleSpinboxHeavyComputation::DoubleSpinboxHeavyComputation(QWidget *parent)
: QWidget(parent), ui(new Ui::DoubleSpinboxHeavyComputation)
{
ui->setupUi(this);
connect(ui->doubleSpinBox, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
&DoubleSpinboxHeavyComputation::startHeavyComputationInThread);
}
DoubleSpinboxHeavyComputation::~DoubleSpinboxHeavyComputation()
{
delete ui;
}
void DoubleSpinboxHeavyComputation::startHeavyComputationInThread()
{
if (ui->checkBox->isChecked())
{
QProgressDialog *progress = new QProgressDialog("Computing", "", 0, 0, this);
progress->setWindowTitle(windowTitle());
progress->setWindowFlags((progress->windowFlags() | Qt::CustomizeWindowHint) &
~Qt::WindowCloseButtonHint); // Hide close button
progress->setWindowModality(Qt::WindowModal);
progress->setCancelButton(nullptr);
progress->setMaximum(1000);
progress->show();
connect(this, &DoubleSpinboxHeavyComputation::progressSignal, progress, &QProgressDialog::setValue);
connect(this, &DoubleSpinboxHeavyComputation::computationDone, progress, &QProgressDialog::close);
connect(this, &DoubleSpinboxHeavyComputation::computationDone, progress, &QProgressDialog::deleteLater);
}
QtConcurrent::run(this, &DoubleSpinboxHeavyComputation::heavyComputation);
}
void DoubleSpinboxHeavyComputation::heavyComputation()
{
int current_n = n_;
++n_;
qDebug() << "Start computation " << current_n;
for (int i = 0; i < 1000; i++)
{
emit progressSignal(i);
usleep(1000);
}
qDebug() << "End computation" << current_n;
emit computationDone();
}
最佳答案
看起来您需要继承QDoubleSpinbox
和重新实现textFromValue
方法
class NumericEdit : public QDoubleSpinBox
{
Q_OBJECT
public:
NumericEdit(QWidget *p_parent = nullptr);
QString textFromValue(double val) const;
};
QString NumericEdit::textFromValue(double val) const
{
//default converting
// return QString::number(val);
//converting with a local representation
QLocale locale;
return locale.toString(val);
}
但这会破坏Spinbox的默认
prefix
和suffix
功能