LCDRange.h
#ifndef LCDRANGE_H_ #define LCDRANGE_H_ #include <QWidget.h> class QSlider; class LCDRange:public QWidget { Q_OBJECT public: LCDRange(QWidget* parent=NULL, const char *name=NULL); int value() const; public slots: void setValue(int); signals://信号只声明,不能定义. void valueChanged(int); private: QSlider *slider; }; #endif//LCDRANGE_H_
LCDRange.cpp
#include "LCDRange.h" #include <QSlider.h> #include <QLCDNumber.h> #include <QVBoxLayout> LCDRange::LCDRange(QWidget* parent, const char *name) :QWidget(parent, name) { QLCDNumber *lcd = new QLCDNumber(2, this); slider = new QSlider(Qt::Orientation::Horizontal, this); slider->setRange(0, 99); slider->setValue(0); //别把display(int)写成Display(int)了,不然不会响应的,而且你就算写成display1, //编译器也不会报错,只是不响应 // connect(slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int))); //信号-->类的信号--> connect(slider, SIGNAL(valueChanged(int)), SIGNAL(valueChanged(int))); QVBoxLayout *vlayout = new QVBoxLayout; vlayout->addWidget(lcd); vlayout->addWidget(slider); setLayout(vlayout); } int LCDRange::value() const { return slider->value(); } void LCDRange::setValue(int value) { slider->setValue(value); }
main
#include "qtlesson.h" #include <QtGui/QApplication> #include <QPushButton.h> #include <QFont.h> #include <QVBoxLayout> #include <QGridLayout> #include "LCDRange.h" class MyWidget : public QWidget { public: MyWidget(QWidget *parent=NULL, const char *name=NULL); }; MyWidget::MyWidget(QWidget* parent, const char *name) { QPushButton *quit = new QPushButton("Quit", this); quit->setFont(QFont(("Times"), 18, QFont::Bold)); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); QVBoxLayout *vlayout = new QVBoxLayout; //QGridLayout,这里和列有关,比如(6,12),因为才12个,那就网格成一行了, QGridLayout *grid = new QGridLayout(6, 12); LCDRange *previous = 0; for (int r=0; r<3; r++) { for (int c=0; c<4; c++) { LCDRange *lr = new LCDRange(this); if (previous) { connect(lr, SIGNAL(valueChanged(int)), previous, SLOT(setValue(int))); } grid->addWidget(lr); previous = lr; } } vlayout->addWidget(quit); vlayout->addLayout(grid); setLayout(vlayout); } int main(int argc, char *argv[]) { QApplication a(argc, argv); MyWidget w; a.setMainWidget(&w); w.show(); return a.exec(); }
1.QGridLayout,和列有关,比如(6,12),因为才12个,那就网格成一行了,
2.信号只声明,不能定义.一定义就提示错误
3.信号的调用可以通过emit valueChanged(xx)这样被其他调用
4.connect好像不做代码检查的,也就是无论SIGNAL()和 SLOT()中填的是不是已存在的函数,它都认为OK,编译通过