Send signal from QSlider to QLineEdit slot

74 views Asked by At

I have a horizontal slider, and I want a line edit updated when the slider value is changed.

I wrote this, but nothing happens:

connect(ui->horizontalSlider1, SIGNAL(&QSlider::valueChanged), ui->lineEdit2, SLOT(&QLineEdit::setText));

I can see that the valueChanged has a parameter of type int, but the setText takes a parameter of a different type.

I don't get an error during build, and nothing happens when I run the application.

What is the correct way of doing this?

2

There are 2 answers

0
quantum231 On

First update the MainWindow class inside the mainwindow.h:

private:
    Ui::MainWindow *ui;
    void updateLineEdit(int);

Then use this as the contents of the mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton1, SIGNAL(clicked()), ui->lineEdit1, SLOT(clear()));

    connect(ui->horizontalSlider1, &QSlider::valueChanged, this, &MainWindow::updateLineEdit);

}

void MainWindow::updateLineEdit(int value) {
    this->ui->lineEdit2->setText(QString::number(value));
}

MainWindow::~MainWindow()
{
    delete ui;
}
1
hyde On

First of all, your syntax is wrong, right would be
connect(ui->horizontalSlider1, &QSlider::valueChanged, ui->lineEdit2, &QLineEdit::setText);

However, the parameter types don't match, so this won't work. Your purpose is best served by a lambda:

connect(ui->horizontalSlider1, &QSlider::valueChanged, 
        // use context ui-lineEdit2, capture "this" by value,
        // match lamba parameters with the signal parameters
        ui->lineEdit2, [this](int value){ 
             // "this" was captured, so it is implicitly used in line below,
             // and format the integer as numeric string any way you need
             ui->lineEdit2->setText(QString::number(value));
});