Qtf.h
#include <QtWidgets/QWidget>
#include "ui_Qtf.h"
#include <QPushButton>
#include "subWidget.h"
class Qtf : public QWidget
{
Q_OBJECT
public:
Qtf(QWidget *parent = Q_NULLPTR);
public slots:
void myslot();
void mychange();
void mydeal();
private:
QPushButton b1;
QPushButton *b2;
QPushButton b3;
subWidget s;
Ui::QtfClass ui;
};
main.cpp
#include "Qtf.h"
#include <QtWidgets/QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Qtf w;
w.show();
return a.exec();
}
Qtf.cpp
#include "Qtf.h"
Qtf::Qtf(QWidget *parent)
: QWidget(parent)
{
this->setWindowTitle("老大");
b1.setParent(this);
b1.setText("^_^");
b1.move(100, 100);
b2 = new QPushButton;
b2->setParent(this);
b2->setText("Qt!");
connect(&b1, SIGNAL(clicked()), this, SLOT(myslot()));
b3.setParent(this);
b3.setText("切换窗口");
b3.move(50, 50);
connect(&b3, SIGNAL(clicked()), this, SLOT(mychange()));
connect(&s, SIGNAL(mysignal()), this, SLOT(mydeal()));
this->setFixedSize(400, 300);
ui.setupUi(this);
}
void Qtf::myslot()
{
b2->setText("abc");
}
void Qtf::mychange()
{
this->hide();
s.show();
}
void Qtf::mydeal()
{
this->show();
s.hide();
}
subWidget.h
#pragma once
#include <qwidget.h>
#include <QPushButton>
class subWidget :
public QWidget
{
Q_OBJECT
private:
QPushButton button;
signals:
void mysignal();
public slots:
void sendsignal();
public:
subWidget();
~subWidget();
};
subWidget.cpp
#include "subWidget.h"
subWidget::subWidget()
{
this->setWindowTitle("小弟");
this->resize(400, 300);
button.setParent(this);
button.setText("切换到老大");
connect(&button, SIGNAL(released()), this, SLOT(sendsignal()));
}
void subWidget::sendsignal()
{
emit mysignal();
}
subWidget::~subWidget()
{
}
信号与槽:
Qt对象之间的通信接口
connect(&b1, SIGNAL(clicked()), this, SLOT(myslot()));
Q_OBJECT:
The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt’s meta-object system.
指定父对象:
一是通过构造函数,一是setparent().
固定窗口大小:
setFixedSize(width,height)