当前位置:网站首页>QT related problems encountered when writing code
QT related problems encountered when writing code
2022-07-19 08:13:00 【Boya_ Hancook】
qt clicked() function To transfer data
When qt Press down btn It can transfer data ?
Normally, when the key is pressed ,qt Binding slot function is to execute slot function , But if I want to press btn The key slot function can receive data .
Read others' posts saying that anonymous functions can be used lamda Expression implementation . I tried , You can really . So record it .
Go straight to the code :
The key is connect function :
connect(ui.btnPictureSavePath, &QPushButton::clicked, _configFileData.get(), [=] () {_configFileData.get()->ChoosePath(cn); });explain : The first parameter is the pointer of the key , The second parameter is the signal function of space , The third parameter is the slot pointer, and the fourth parameter is lamda expression , And that's the key point . We need to pay attention to .
[=] () {_configFileData.get()->ChoosePath(cn); }
_configFileData.get() This one uses get Function is because _configFileData This pointer I use is a smart pointer , Use get Get the original pointer .
This binding function cannot be used &_configFileData.get()->ChoosePath(cn) In this way , This is a mistake .
QT Number of read files :
std::shared_ptr<QDir> dir = std::make_shared<QDir>(path);
QStringList filter;
QFileInfoList fileInfoList = dir->entryInfoList(filter);
int peopleNum = fileInfoList.count() - 2;Need to add header file #include <QDir>
path yes QString Storage path , It doesn't have to be QString Can only be string It's OK, too , As long as it is a string .
int peopleNum = fileInfoList.count() - 2; Why subtract two , Because there are two default folders under each folder , One is “.” One is “..”, It means the current folder and the upper folder , All to be reduced 2.
fileInfoList What is stored here is the name of the folder , The first and second stores "." and "..". From the third, there are files under the file .
QT read txt Data and calculate the number of trips and columns :
This txt What is stored is a matrix data , Probably like this

In this way, the number of rows and columns of this matrix can be read quickly ?
Code :
int row = -1;
int line = -1;
QFile file(path + "/s1_1.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Can't open the file!" << endl;
}
QByteArray byte = file.readLine();
QString str(byte);
QStringList strList = str.split(" ");
strList.removeAll("");
line = strList.size();
row = file.size() / file.readLine().size();QFile file(path + "/s1_1.txt"); This line of code is to open txt file .
QByteArray byte = file.readLine(); This line of code reads txt One line of data , Note that this data is not what we see txt In the middle of , You can understand this as char data , It's character by character . So the length of this data type is much larger than txt Medium double data .
QString str(byte); This sentence is binary into string form .
QStringList strList = str.split(" "); The string is separated by spaces , There is a space in the middle .
strList.removeAll(""); This sentence is to delete the extra space , Because of me txt In order to tab separated , So there are many spaces after separating with spaces , That's why there is the sentence of deleting the spaces used , This sentence is not necessary if it is separated by a single control lattice .
line = strList.size(); This sentence is to find out how many there are in a row double data , That is, the columns of the matrix .
The solution of the number of rows is actually very simple , It's reading TXT All binaries of the file are not then divided by the binary number on a line .
row = file.size() / file.readLine().size(); That is to say .
qt Reading and writing json:
my json file :
{
"Data": {
"EEGChannel": 32,
"Frequency": 128,
"FrequencyTime": 60,
"PointNum": 7681,
"path": "F:/code/data/EEG",
"peopleNum": 32,
"testNum": 40
},
"GUI": {
"IsOpenTimer": false,
"TimerPrecision": "",
"style": -1
},
"SQL": {
"IsOpenSQL": false
},
"Text": {
"path": ""
},
"cudaConfig": {
"IsOpen": false
},
"log": {
"KeepTheDate": -1
},
"picture": {
"IsSavePicture": false,
"path": ""
},
"wavelet": {
"depth": -1
}
}
Read and write functions :
void ConfigFileData::RWConfigFile(bool b)
{
std::shared_ptr<FileOperation> _fileOperation = std::make_shared<FileOperation>();
if (b)// true read configuration file ,false Write profile
{
QString strConfig = _fileOperation->readJSON(_configFilePath);
QJsonParseError parseJsonErr;
QJsonDocument document = QJsonDocument::fromJson(strConfig.toUtf8(),&parseJsonErr);
if (!(parseJsonErr.error == QJsonParseError::NoError))
{
QMessageBox::about(NULL," Tips "," Configuration file error !");
return;
}
QJsonObject jsonObject = document.object();
/****GUI******/
QJsonValue jsonGUIValue = jsonObject.value(QStringLiteral("GUI"));
QJsonObject jsonGUIData = jsonGUIValue.toObject();
_initialized->SetGUIStyle(jsonGUIData["style"].toInt());
_initialized->SetGUIIsOpenTimer(jsonGUIData["IsOpenTimer"].toBool());
_initialized->SetGUITimerPrecision(jsonGUIData["TimerPrecision"].toString());
/******CUDA****/
QJsonValue jsonCUDAConfigValue = jsonObject.value(QStringLiteral("cudaConfig"));
QJsonObject jsonCUDAConfigData = jsonCUDAConfigValue.toObject();
_initialized->SetCudaConfigIsOpen(jsonCUDAConfigData["IsOpen"].toBool());
/********Picture***/
QJsonValue jsonPictureValue = jsonObject.value(QStringLiteral("picture"));
QJsonObject jsonPictureData = jsonPictureValue.toObject();
_initialized->SetPictureIsSavePicture(jsonPictureData["IsSavePicture"].toBool());
_initialized->SetPicturePath(jsonPictureData["path"].toString());
/*******Wavelet**********/
QJsonValue jsonWaveletValue = jsonObject.value(QStringLiteral("wavelet"));
QJsonObject jsonWaveletData = jsonWaveletValue.toObject();
_initialized->SetWaveletDepth(jsonWaveletData["depth"].toInt());
/****Text****/
QJsonValue jsonTextValue = jsonObject.value(QStringLiteral("Text"));
QJsonObject jsonTextData = jsonTextValue.toObject();
_initialized->SetTextPath(jsonTextData["path"].toString());
/*****Log*********/
QJsonValue jsonLogValue = jsonObject.value(QStringLiteral("log"));
QJsonObject jsonLogData = jsonLogValue.toObject();
_initialized->SetLogKeepTheDate(jsonLogData["KeepTheDate"].toInt());
_initialized->SetLogPath(jsonLogData["Path"].toString());
/****SQL*********/
QJsonValue jsonSQLValue = jsonObject.value(QStringLiteral("SQL"));
QJsonObject jsonSQLData = jsonSQLValue.toObject();
_initialized->SetSQLIsOpenSQL(jsonSQLData["IsOpenSQL"].toBool());
/****data*************/
QJsonValue jsonDataValue = jsonObject.value("Data");
QJsonObject jsonDataData = jsonDataValue.toObject();
_initialized->SetDataPath(jsonDataData["path"].toString());
_initialized->SetDataPeopleNum(jsonDataData["peopleNum"].toInt());
_initialized->SetDataTestNum(jsonDataData["testNum"].toInt());
_initialized->SetDataEEGChannel(jsonDataData["EEGChannel"].toInt());
_initialized->SetDataPointNum(jsonDataData["PointNum"].toInt());
_initialized->SetDataFrequency(jsonDataData["Frequency"].toInt());
_initialized->SetDataFrequencyTime(jsonDataData["FrequencyTime"].toInt());
}
else
{
QJsonObject jsonInitialized;
/*****GUI****/
QJsonObject guiJson;
guiJson.insert("style",_initialized->GetGUIStyle());
guiJson.insert("IsOpenTimer",_initialized->GetGUIIsOpenTimer());
guiJson.insert("TimerPrecision",_initialized->GetGUITimerPrecision());
jsonInitialized.insert("GUI",guiJson);
/****CUDA*******/
QJsonObject cudaConfigJson;
cudaConfigJson.insert("IsOpen",_initialized->GetCudaConfigIsOpen());
jsonInitialized.insert("cudaConfig",cudaConfigJson);
/****Picture**********/
QJsonObject pictureJson;
pictureJson.insert("IsSavePicture",_initialized->GetPictureIsSavePicture());
pictureJson.insert("path",_initialized->GetPicturePath());
jsonInitialized.insert("picture", pictureJson);
/*****Wavelet************/
QJsonObject waveletJson;
waveletJson.insert("depth",_initialized->GetWaveletDepth());
jsonInitialized.insert("wavelet",waveletJson);
/*****Text*******/
QJsonObject textJson;
textJson.insert("path",_initialized->GetTextePath());
jsonInitialized.insert("Text",textJson);
/*****Log**********/
QJsonObject logJson;
logJson.insert("KeepTheDate",_initialized->GetLogKeepTheDate());
jsonInitialized.insert("log",logJson);
/*****SQL************/
QJsonObject SQLJson;
SQLJson.insert("IsOpenSQL",_initialized->GetSQLIsOpenSQL());
jsonInitialized.insert("SQL",SQLJson);
/*****data**********/
QJsonObject DataJson;
DataJson.insert("path",_initialized->GetDataPath());
DataJson.insert("peopleNum",_initialized->GetDataPeopleNum());
DataJson.insert("testNum",_initialized->GetDataTestNum());
DataJson.insert("EEGChannel",_initialized->GetDataEEGChannel());
DataJson.insert("PointNum",_initialized->GetDataPointNum());
DataJson.insert("Frequency",_initialized->GetDataFrequency());
DataJson.insert("FrequencyTime",_initialized->GetDataFrequencyTime());
jsonInitialized.insert("Data",DataJson);
/*****JSON************/
QJsonDocument document(jsonInitialized);
QByteArray byteArray = document.toJson(QJsonDocument::Indented);
QString strJson(byteArray);
_fileOperation->write_string_to_file_append(GetConfigFilePath().toStdString(), strJson.toStdString(), std::ios::ate | std::ios::out);
}
}
QByteArray byteArray = document.toJson(QJsonDocument::Indented);
The difference between line feed and no line feed is the parameter Indented and Compact The difference between .
hold json Write to file :
bool FileOperation::write_string_to_file_append(const std::string& file_string, const std::string str, int model)
{
std::ofstream OsWrite(file_string, model);
OsWrite << str;
OsWrite << std::endl;
OsWrite.close();
return 0;
}QT Binding of signal slot function connect function :
I met a pit today , A problem about signal slot function binding .
UI A space of QComboBox, I want to use one of the signal functions activated To send data , Then write an acceptance function of your own class . When I follow Qt5 Write in the recommended way , Later, I read a book and said that the binding function uses the form of function pointer signal function , Functions with different parameters and the same name cannot be in the form of function pointers .
So you can only use old-fashioned binding functions .demo:
connect(ui.WaveletDepth,SIGNAL(activated(int)), _configFileData.get(), SLOT(SetWaveletDepth(int)));This binding function , The first argument is the function pointer , The second parameter is a macro definition , Inside is the function name , There is no need to specify that kind , Because the first parameter has been specified . The third parameter is the receiver's pointer , The fourth parameter is also a macro definition , It's a function , There is no need to specify a class .
New binding functions :
connect(ui.btnPictureSavePath, &QPushButton::clicked, _configFileData.get(), [=] () {_configFileData.get()->ChoosePath(cn); });边栏推荐
- Bean、
- Classic general pbootcms flower website template source code, adaptive mobile terminal, with background management
- How to use curl in Jenkins pipeline and process response results
- 【flask入门系列】请求钩子与上下文
- 数组习题三
- Shenzhen Prudential written examination record
- [C console] - C console class
- [C # console] - C # console class
- Redis distributed lock
- Niuke topic - house raiding 1, house raiding 2
猜你喜欢

Ccf-csp "202206-2 - treasure hunt! Adventure!"

Jira --- workflow call external api

分叉币的发展史及价值|ETH、BCH、BSV 2020-03-08

深度学习之 7 深度前馈网络2

New redis6 features

Code learning (deamnet) CVPR | adaptive consistency prior based deep network for image learning

STM32F103C8T6硬件IIC控制4针0.96寸OLED显示屏

By voting for the destruction of STI by Dao, seektiger is truly community driven

Array exercise 3

redis消息订阅
随机推荐
Redis storage structure principle 2
Is there any cumulative error in serial communication and the requirements for clock accuracy
[MySQL] lock mechanism: detailed explanation of lock classification, table lock, row lock and page lock in InnoDB engine
Ku115 FPGA high performance 10G Optical fiber network hardware accelerator card / 2-way 10G Optical fiber data accelerator card
OI回忆录
Using PCA to simplify data
经典通用的Pbootcms花卉网站模板源码,自适应手机端,带后台管理
Unity custom sky ball model to prevent it from being cropped
通过ip获取归属地
剑指 Offer 42. 连续子数组的最大和-动态规划法
redis消息订阅
redis集群
Complete square number
从赌场逻辑,分析平台币的投资价值 2020-03-03
Visual studio production environment configuration scheme: slowcheetah
175. Combine two tables (MySQL database connection)
YOLOV5-打标签建立自己的数据集
Is it necessary to buy pension insurance? What are the pension products suitable for the elderly?
在VSCode中设置settings.json
聊聊分布式锁