首页 > 解决方案 > Qt how to connecto Line Edit to progress bar

问题描述

I am very new to QT and C++, I am trying to connect Line edit to progress bar so when I enter some integer value to the Line Edit, progress bar will show it. I could not achieve it. This is what I was trying:

    connect(ui->batterycapacity,&QLineEdit::textChanged, ui->progressBar,ui->progressBar->setValue(ui->batterycapacity->text().toInt()));

or this:

    connect(ui->batterycapacity,&QLineEdit::textChanged, ui->progressBar,ui->progressBar->&QProgressBar::setValue(ui->batterycapacity->text().toInt()));

batterycapacity is my Line Edit. How can I connect those 2 together? Thanks beforehand.

标签: c++qt

解决方案


你很近。由于信号的参数与槽的参数不同,您需要对其进行调整toInt,但您不能简单地将任意代码粘贴在参数中并期望 C++ 在信号更改时执行它。

您需要将代码段包装在lambda 表达式中:

connect(ui->batterycapacity, &QLineEdit::textChanged, ui->progressBar,
  [=](const QString& text) {
    ui->progressBar->setValue(text.toInt()));
  });

lambda 将接收textChanged信号的参数并将其传递给setValue方法。[=]前面的位告诉编译器按值捕获 的值,ui以便在 lambda 内部可以访问它。


推荐阅读