信号和槽函数连接的语法要求
1.信号和槽参数要一致
QObject::connect(A,SIGNAL(sigfun(int)),B,SLOT(slotfun(int)));//ok
QObject::connect(A,SIGNAL(sigfun(int)),B,SLOT(slotfun(int,int)));//error
2.可以带有缺省参数
QObject::connect(A,SIGNAL(sigfun(int)),B,SLOT(slotfun(int,int=0)));//ok
3.信号的参数可以多于槽函数,多于参数将被忽略
QObject::connect(A,SIGNAL(sigfun(int,int)),B,SLOT(slotfun(int)));//ok
#include<QApplication>
#include<QHBoxLayout>
#include<QSlider>
#include<QSpinBox>
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
QWidget* window = new QWidget;
window->setWindowTitle("Enter Your Age:");
QSpinBox* spinBox = new QSpinBox;
QSlider* slider = new QSlider(Qt::Horizontal);
QObject::connect(spinBox,SIGNAL(valueChanged(int)),slider,SLOT(setValue(int)));
QObject::connect(slider,SIGNAL(valueChanged(int)),spinBox,SLOT(setValue(int)));
//一个对象数值改变,就会emit另外一个对象进行参数设置
spinBox->setValue(35);
//将spinBox的值设置为35,spinBox发射valueChanged(int)信号,参数int的值是35,这个参数
//会被传递给slider的setValue(int)槽,slider的值变为35后,发射了valueChanged(int)信号,
//传递给slider的setValue(int)槽,但是此时slider已经是35了,所以不再发射valueChanged(int)信号。
QHBoxLayout* layout = new QHBoxLayout;
layout->addWidget(spinBox);
layout->addWidget(slider);
window->setLayout(layout);
window->show();
return app.exec();
}
使用QMetaObject::connectSlotsByName(this);
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSlider>
#include <QSpinBox>
#include <QVBoxLayout>
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
public:
QVBoxLayout *verticalLayout;
QSpinBox *spinBox;
QSlider *slider;
private slots:
void on_spinBox_valueChanged(int arg1);
void on_slider_valueChanged(int value);
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) : QWidget(parent)
{
// this->resize(400, 300);
verticalLayout = new QVBoxLayout(this);
// verticalLayout->setSpacing(6);
// verticalLayout->setContentsMargins(11, 11, 11, 11);
// verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
spinBox = new QSpinBox(this);
spinBox->setObjectName(QStringLiteral("spinBox"));//务必设置ObjectName,因为信号槽要用到
verticalLayout->addWidget(spinBox);
slider = new QSlider(Qt::Horizontal);
// slider->setOrientation(Qt::Horizontal);
slider->setObjectName(QStringLiteral("slider"));//务必设置ObjectName,因为信号槽要用到
verticalLayout->addWidget(slider);
setLayout(verticalLayout);
QMetaObject::connectSlotsByName(this);//根据ObjectName来调用槽函数
}
void Widget::on_spinBox_valueChanged(int arg1)
{
qDebug() << arg1;
slider->setValue(arg1);
}
void Widget::on_slider_valueChanged(int value)
{
qDebug() << value;
spinBox->setValue(value);
}
Widget::~Widget()
{
}