您的位置:首页 > 编程语言 > Qt开发

QT5(4)代码实现应用及信号槽实例

2016-10-06 23:45 344 查看

一、基于Qt5的代码

除了使用Qt的《设计》来快速添加控件,同样可以使用代码来添加控件。

二、新建项目

在新建项目过程中时取消创建界面,Qt将不会帮我们创建UI代码,需要我们手工添加。



三、添加代码

1、在mainwindow.h中添加如下代码:



#include <QLabel>
#include <QLineEdit>
#include <QPushButton>


private:
QLabel *label_1,*label_2;
QLineEdit *lineEdit_1;
QPushButton *button_1;


2、在mainwindow.cpp中添加如下控件:



QWidget *cenWidget = new QWidget(this);  //记得在头文件中包括QWidget
setCentralWidget(cenWidget);

label_1 = new QLabel(cenWidget);
label_1->setText(tr("请输入:"));
label_2 = new QLabel(cenWidget);
lineEdit_1 = new QLineEdit(cenWidget);
button_1 = new QPushButton(cenWidget);
button_1->setText(tr("显示面积"));

QGridLayout *mainLayout = new QGridLayout(cenWidget);
mainLayout->addWidget(label_1, 0, 0);
mainLayout->addWidget(lineEdit_1, 0, 1);
mainLayout->addWidget(label_2, 1, 0);
mainLayout->addWidget(button_1, 1, 1);

connect(button_1, SIGNAL(clicked()), this, SLOT(showArea())); // 此处是对相应控件绑定clicked事件


3、在mainwindow中添加如下控件:

声明信号槽函数:



private slots:
void showArea();


实现信号槽函数:



void MainWindow::showArea(){
bool ok;
QString tempStr;
QString valueStr = lineEdit_1->text();
int valueInt = valueStr.toInt(&ok);
double area = valueInt*valueInt*3.14;
label_2->setText(tempStr.setNum(area));
}


四、注意问题

1、出现 Attempting to add QLayout “” to MainWindow “”, which already has a layout

解决:布局layout新建对象时参数使用this,而mainwindow中其实已存在一个layout。不要使用this

2、在mainwindow中添加多个控件,控件却重叠只显示最后一个。

解决:

Note: Creating a main window without a central widget is not supported. You must have a central widget even if it is just a placeholder.

添加如下代码:

QWidget *cenWidget = new QWidget(this);  //添加该行
setCentralWidget(cenWidget);             //添加该行

label_1 = new QLabel(cenWidget);   //注意参数
label_1->setText(tr("请输入:"));
label_2 = new QLabel(cenWidget);   //注意参数
lineEdit_1 = new QLineEdit(cenWidget);    //注意参数
button_1 = new QPushButton(cenWidget);    //注意参数
button_1->setText(tr("显示面积"));

QGridLayout *mainLayout = new QGridLayout(cenWidget);    //注意参数
mainLayout->addWidget(label_1, 0, 0);


3、使用信号槽注意事项:

信号函数与槽函数参数类型必须按顺序对应;槽函数参数个数可少于信号函数参数个数,且按顺序对应,多余参数会自动忽略。

发出信号函数:emit iSignal(“信号发出”);

4、connect参数传递解决办法:

// 1、重载相应类的信号函数

// 2、自定义信号函数和槽函数

// 3、直接在类内部定义个成员变量,或者弄个全局变量
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  qt5 qt