Search code examples
qtqt4qt-creatorsignals-slots

Signal and Slot in Qt4 - not working


I am using Qt4 and Qt Creator. I cannot write a custom slot to a progress bar in the UI. How to write a custom slot for a specific widget in the ui file ? In my scenario, signal is not from the ui element.

the below code produces an error while running:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QFile>
#include<QFileInfo>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_btcopy_clicked();
    void on_btquit_clicked();
    void ChangeValue(qint64 val);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btcopy_clicked()
{
    QFileInfo *qfi=new QFileInfo("C:\\Users\\kiran\\Desktop\\test\\a.iso");
    qDebug("%d" ,qfi->size());
    QFile *qf=new QFile();
    QFile fromFile("C:\\Users\\kiran\\Desktop\\test\\a.iso");
    QFile toFile("C:\\Users\\kiran\\Desktop\\test\\b.iso");
    ui->pbar->setMaximum(fromFile.size());
    fromFile.copy(toFile.fileName());

    connect(&toFile, SIGNAL(bytesWritten(qint64)), ui->pbar, SLOT(CangeValue(qint64)));
    qDebug("completed");
}

void MainWindow::on_btquit_clicked()
{
   exit(0);
}

void MainWindow::CangeValue(qint64 val)
{
    ui->pbar->setValue(val);
}

Error Message

Object::connect: No such slot ProgressBar::CangeValue(qint64)in..\untitled\mainwindow.cpp:26
    Object::connect:  (receiver name: 'pbar')

Solution

  • CangeValue is a slot in your MainWindow (for the record: it should be called ChangeValue).

    Therefore the third parameter in your connect(..) statement must be your main window, not the progress bar. Replace ui->pbar by this in your connect statement.