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、直接在类内部定义个成员变量,或者弄个全局变量
相关文章推荐
- 利用discuz实现PHP大文件上传应用实例代码
- submit应用实例全面实现一段代码多次使用(ALV显示然后打印)
- Vue.js实现实例搜索应用功能详细代码
- 利用discuz实现PHP大文件上传应用实例代码
- 为Windows应用创建简单的异步调用模式(附实例代码)
- 简单SNMP管理程序的VC++代码实例实现
- 技术沙龙.:主题为《代码解析Castle(IOC)应用实例 -开源CMS 系统Cuyahoga》
- 技术沙龙.:主题为《代码解析Castle(IOC)应用实例 -开源CMS 系统Cuyahoga》
- SP 短信开发-PROVISION接口实现-反向取消实例代码
- [原创]ASP.net 2.0 ObjectDataSource 应用操作代码实例(1)-—访问SQL2005
- 基于.Net平台应用程序唯一运行实例C#代码实现
- 技术沙龙.:主题为《代码解析Castle(IOC)应用实例 -开源CMS 系统Cuyahoga》
- ASP + Serv-u 实现FTP的代码- ASP 实例
- Java批注的发明起因及代码应用实例
- JS中封装解析xml的代码,以及实例应用
- 简单SNMP管理程序的VC++代码实例实现
- 简单SNMP管理程序的VC++代码实例实现
- ASP实例:6行代码实现无组件上传
- 应用框架的设计与实现——.NET平台4.2代码测试问题解决
- 实例分析之用ASP编程实现网络内容快速查找的代码