当前位置:网站首页>[Qt5] a method of multi window parameter transmission (using custom signal slot) and case code download
[Qt5] a method of multi window parameter transmission (using custom signal slot) and case code download
2022-07-28 08:27:00 【qilei2010】
2021-12-29 to update Qt5 New and old versions of the signal - Writing method of groove Pay special attention to instructions .
Qt5 The old grammar of ( Use SIGNAL The macro and SLOT macro ):
connect(sender, SIGNAL(valueChanged(QString, QString)),
receiver, SLOT(updateValue(QString)));Qt5 New syntax ( Use function pointers ):
//Qt5 Signals and slots without parameters A new way of writing
connect(sender, &Sender::valueChanged,
receiver, &Receiver::updateValue);Signals and slots with parameters :
//Qt5 A new way to write signals and slots with parameters in
// The previously declared signal , The signal must return void, And there's no need to implement
signals:
void my_signal(int,QString);
// The previously declared slot , The slot must return void, Need to achieve
slots:
void print_signal(int, QString);
// When used later , To turn into Pointer to class member function Reuse later
void (Widget::*signal_with_para)(int,QString) = &Widget::my_signal; // With parameter signal
void (Widget::*slot_with_para)(int,QString) = &Widget::print_signal; // With parameter slot
connect(btn2, signal_with_para, this, slot_with_para); // Processing signals with parameters Qt Official description of the new grammatical format :
Be careful : The officially emphasized slot function type is PointerToMemberFunction , Meaning for Point to Pointer to class member function , It can be a pointer to any class member function . therefore ,& We need to keep up Class modifier ::.
The following quotations can be found in Qt Creator Choose connect function , Then press F1 Key can be seen in the corresponding help document .
[static] QMetaObject::Connection QObject::connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection)
This function overloads connect().
Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns a handle to the connection that can be used to disconnect it later.
The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.
Example:
QLabel *label = new QLabel;QLineEdit *lineEdit = new QLineEdit;QObject::connect(lineEdit, &QLineEdit::textChanged,label, &QLabel::setText);This example ensures that the label always displays the current line edit text.
A signal can be connected to many slots and signals. Many signals can be connected to one slot.
If a signal is connected to several slots, the slots are activated in the same order as the order the connection was made, when the signal is emitted
The function returns an handle to a connection if it successfully connects the signal to the slot. The Connection handle will be invalid if it cannot create the connection, for example, if QObject is unable to verify the existence of signal (if it was not declared as a signal) You can check if the QMetaObject::Connection is valid by casting it to a bool.
By default, a signal is emitted for every connection you make; two signals are emitted for duplicate connections. You can break all of these connections with a single disconnect() call. If you pass the Qt::UniqueConnection type, the connection will only be made if it is not a duplicate. If there is already a duplicate (exact same signal to the exact same slot on the same objects), the connection will fail and connect will return an invalid QMetaObject::Connection.
The optional type parameter describes the type of connection to establish. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time. If the signal is queued, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes. If you try to use a queued connection and get the error message
QObject::connect: Cannot queue arguments of type 'MyType'(Make sure 'MyType' is registered using qRegisterMetaType().)make sure to declare the argument type with Q_DECLARE_METATYPE
Overloaded functions can be resolved with help of qOverload.
Note: This function is thread-safe.
See also Differences between String-Based and Functor-Based Connections.
Qt5 See this article for the advantages and benefits of the new writing method :
The following is a original text :
Self reference .
After the achievement change of each subject , The total score is automatically updated .
That is many QLineEdit launch textChanged() The signal , Single slot ( Self made function calc() ) receive , Realize many to one connection .
1. Qt Native controls
Qt Native controls , It has enough signals . stay UI In the interface , Right click the control , choice “ Go to slot ”, You will be prompted to select “ The signal ”, We can choose the right signal .
1.1 The header file mainwindow.h
Add... To the header file Slot function declaration . Note that the parameters of the slot function should be consistent with those of the signal function .
// Because it is used later Date and time , Here you need to add the corresponding header file
#include <QDate>
#include <QTime>
#include <QDateTime>
...
private slots:
void calc(const QString &mystr);1.2 Class file mainwindow.cpp
1.2.1 Constructors add to Signal to slot correlation connect
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(calc(QString)));
connect(ui->lineEdit_2, SIGNAL(textChanged(QString)), this, SLOT(calc(QString)));
connect(ui->lineEdit_3, SIGNAL(textChanged(QString)), this, SLOT(calc(QString)));
}Be careful :
A. The signal function should use SIGNAL() The parcel , Slot function should use SLOT() The parcel .
B. Signal functions can take parameters , but Do not specify the return value type .
C. The parameters of signal function and slot function are Do not specify the parameter name , Only parameter types are required .
D. Signal function and slot function Number of parameters 、 type Agreement .
E. The signal function can be Qt Component's Defined function , It can also be a function defined by itself .
1.2.2 Implementation code of slot function
/*
Remember in mainwindow.h Add Date and time header file reference
#include <QDate>
#include <QTime>
#include <QDateTime>
*/
void MainWindow::calc(const QString & mystr)
{
// mystr Receive the parameters of the signal
this->log.append(" Input :"+mystr);
this->log.append("\t");
//sum
int chinese = ui->lineEdit->text().toInt();
int math = ui->lineEdit_2->text().toInt();
int english = ui->lineEdit_3->text().toInt();
int sum = chinese + math + english;
this->log.append(" Total score :"+QString::number(sum));
this->log.append("\t");
if(sum >= 60*3){
ui->labelR->hide();
ui->labelG->show();
this->log.append(" Pass the total score : yes ");
this->log.append("\t");
}else{
ui->labelG->hide();
ui->labelR->show();
this->log.append(" Pass the total score : no ");
this->log.append("\t");
}
this->log.append(" Time :"+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
this->log.append("\n");
ui->textEdit->setText(this->log);
}

1.3 The code download
Qt5 Multi signal single slot example .zip- Desktop system document resources -CSDN download
It has little reference significance . Compile environment :Qt 5.9.3, Qt Creator 4.4.1, Windows 10 x64.
2. Custom signal
If we need to get data from a pop-up window , Now How do pop-up windows send data to the main window .
Our main interface only Three results , At this time, we need to do Pop up dialog , The pop-up dialog box will list all students and their student numbers 、 Class information , The user clicks to select . Then send the selected student information Pass to main window .
Now , And that's what happened 2 individual class : mainWindow and dialog. The two cannot reference and change each other's controls and data . At this time, the data transmission between them , You can use Custom signals .
such as , Here is the implementation The student in the dialog box is selected , And after confirmation , Send student data to the main window .
2.1 The header file dialog.h
Dialog class can use Qt Creator Use graphical interface to create .
This signal should be declared in the header file . The declaration of signals is similar to that of functions .
// Because it is used later Date and time , Here you need to add the corresponding header file
#include <QDate>
#include <QTime>
#include <QDateTime>
#include <QFile>
#include <QDialog>
#include <QListWidget>
#include <QListWidgetItem>
#include <QTextStream>
#include <QDebug>
...
signals:
void sendData(QString);
private slots:
void calc(const QString &mystr);2.2 Class file dialog.cpp
In a function , Send a signal . Be careful , Than ordinary function calls , More than a Prefix emit.
// Qt
void Dialog::on_buttonBox_accepted()
{
// The operation of selecting students is omitted here
// Suppose you have selected and got the student's name Li Si
QString stuName = " Li Si "
// Send a signal
emit sendData(stuName);
}2.3 Main window class header file mainwindow.h
Declare dialog object . Declare the slot that receives the signal . Declaration of slots and Function declarations are similar .
// Qt5
#include <QMainWindow>
#include <QMessageBox>
#include <QFile>
#include <QDialog>
#include <QListWidget>
#include <QListWidgetItem>
#include "dialog.h" // Remember to reference the dialog header file
//...
private:
Ui::Pressure *ui;
QDialog *dlg;
private slots:
void receiveData(QString data)2.4 Main window class file mainwindow.cpp
At class initialization time , Create dialog objects , And establish the correlation between the signal and the slot .
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Test of parent-child window value transmission in signal slot mode
MainWindow::dlg = new Dialog;
// Correlation signal and slot function
connect(dlg,SIGNAL(sendData(QString)),this,SLOT(receiveData(QString)));
// dlg->setModal(true); Whether modal or non modal, values can be transferred normally
//dlg->show();
}
The second part refers to this article :Qt Child window parent window switch , Value transfer between windows _toforu-CSDN Blog _qt Pass values from parent-child window
边栏推荐
- 解决CNN固有缺陷!通用 CNN 架构CCNN来了| ICML2022
- Opencv's practical learning of credit card recognition (4)
- Es6: template string
- See how Google uses pre training weights in target detection tasks | CVPR 2022
- What happens when you unplug the power? Gaussdb (for redis) dual life keeps you prepared
- JS candy xiaoxiaole game source code
- 2022/7/27 examination summary
- Recommend a fully open source, feature rich, beautiful interface mall system
- [300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VIII)
- Allure use
猜你喜欢

Chairman tree review

Prescan quick start to proficient in lecture 17, speed curve editor

华为高级工程师---BGP路由过滤及社团属性
![Redis of non relational database [detailed setup of redis cluster]](/img/0b/bd05fb91d17f6e0dc9f657a4047ccb.png)
Redis of non relational database [detailed setup of redis cluster]

解决CNN固有缺陷!通用 CNN 架构CCNN来了| ICML2022

Melt cloud x chat, create a "stress free social" habitat with sound

Es6: arrow function usage

See how Google uses pre training weights in target detection tasks | CVPR 2022

五张图看懂EMI电磁干扰的传播过程-方波陡峭程度对高频成分的影响,时序到频域频谱图形,波形形状对EMI辐射的影响。

Understand CDN
随机推荐
Common solutions for distributed ID - take one
Regular expression for mobile number verification
Will ordinary browsers disclose information? How to protect privacy by using a secure browser?
非关系型数据库之Redis【redis安装】
What are the different tables in MySQL?
【13】加法器:如何像搭乐高一样搭电路(上)?
0727~ sorting out interview questions
Record a MYCAT connection and solve the problems of communications link failure
What if the computer folder cannot be renamed?
Redis of non relational database [detailed setup of redis cluster]
03 | project deployment: how to quickly deploy a website developed based on the laravel framework
[book club issue 13] Chapter 2 notes on the packaging format and coding format of video files
对spark算子aggregateByKey的理解
Mysql中有哪些不同的表格?
Opencv's practical learning of credit card recognition (4)
The even number of an integer queue is placed in the front, the odd number is placed in the back, and the relative position of the even and odd numbers remains unchanged
Prescan quick start to master the road elements of lecture 15
解决CNN固有缺陷!通用 CNN 架构CCNN来了| ICML2022
[leetcode] 24. Exchange nodes in the linked list in pairs
Understand the propagation process of EMI electromagnetic interference through five diagrams - the influence of square wave steepness on high-frequency components, the spectrum graph from time sequenc