[Using signal(valueChanged) of QSlider to change text of QLabel]
1. your class inherit from class of QObject's children
2. written the keyword "Q_OBJECT" in your code of class
3. use moc(Meta-Object Compiler) to generate a moc file
example:
--------mylabe.h------------
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QLabel>
class mylabel : public QLabel{
Q_OBJECT
public slots:
void setText(int x){
QLabel::setText(QString::number(x));
}
};
#endif // MYLABEL_H
--------main.cpp------------
#include <QApplication>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSlider>
#include <QSpinBox>
#include <QPushButton>
#include "mylabel.moc" <---generated by moc (moc mylabe.h > mylabel.moc)
#include "mylabel.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget;
window->resize(500,600);
window->setWindowTitle("Qt Slots");
QPushButton *button = new QPushButton();
button->setText(QWidget::tr("quit離開"));
QObject::connect(button, SIGNAL(clicked()),&app, SLOT(quit()));
mylabel *label=new mylabel();
QSpinBox *spinBox = new QSpinBox;
QSlider *slider = new QSlider(Qt::Horizontal);
spinBox->setRange(0, 100);
slider->setRange(0, 100);
QObject::connect(spinBox, SIGNAL(valueChanged(int)),slider, SLOT(setValue(int)));
QObject::connect(slider, SIGNAL(valueChanged(int)),spinBox, SLOT(setValue(int)));
QObject::connect(slider, SIGNAL(valueChanged(int)),label, SLOT(setText(int)));
spinBox->setValue(35);
QHBoxLayout *layout = new QHBoxLayout;
QVBoxLayout *vlayout = new QVBoxLayout;
layout->addWidget(spinBox);
layout->addWidget(slider);
vlayout->addLayout(layout);
vlayout->addWidget(label);
vlayout->addWidget(button);
window->setLayout(vlayout);
window->show();
return app.exec();
}
-----
Ref:https://doc.qt.io/qt-5/signalsandslots.html
#QLabel
#QSlider
#QSpinBox
#QPushButton
#Qt
#slot