I am trying to run code of copying files in other thread so that it may not freeze the GUI of the application.
I found that it does not seem to work in a separate thread.
Why is it not working ?
void CopyOperation::run()
{
CopyFilesToFolder(list,sFolder);
}
bool CopyOperation::CopyFilesToFolder(const QStringList &oFileList,const QString
&sTargetFolder)
{
if(sTargetFolder.isEmpty())
{
status = false;
return false;
}
QDir dir(sTargetFolder);
if(!dir.exists()) dir.mkdir(sTargetFolder);
QString sOldDirPath = dir.currentPath();
//if(!dir.setCurrent(sTargetFolder)) return false;
QFile file;
status = true;
foreach(QString sFileName,oFileList)
{
file.setFileName(sFileName);
QFileInfo info(sFileName);
QString newfile = sTargetFolder + "/" + info.fileName();
qDebug() << "\n name = " << newfile;
if(!QFile::copy(sFileName,newfile))
//if(!file.copy(newfile))
{
qDebug() << "\n File copy failed .. " + file.fileName() + " Error : " + file.errorString();
status = false;
break;
}
}
qDebug() << "\n Result .. " << file.errorString() << "code " << file.error();
//dir.setCurrent(sOldDirPath);
return status;
}
Since you didn't post code, I just can try to guess what is the problem. Qt has a static function:
bool copy ( const QString & fileName, const QString & newName )
There is also a copy which is not static:
bool copy ( const QString & newName )
Both of them will fail if file defined by newName already exists, ie. existing file will not be overwritten. Also, maybe path doesn't exists. Without some portion of code is difficult to guess what is the problem.
Related
I have to copy the files from a source directory to a destination directory. Could you please provide the code for doing such operation
I wanted something similar, and was googling (in vain), so this is where I've got to:
static bool cpDir(const QString &srcPath, const QString &dstPath)
{
rmDir(dstPath);
QDir parentDstDir(QFileInfo(dstPath).path());
if (!parentDstDir.mkdir(QFileInfo(dstPath).fileName()))
return false;
QDir srcDir(srcPath);
foreach(const QFileInfo &info, srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot)) {
QString srcItemPath = srcPath + "/" + info.fileName();
QString dstItemPath = dstPath + "/" + info.fileName();
if (info.isDir()) {
if (!cpDir(srcItemPath, dstItemPath)) {
return false;
}
} else if (info.isFile()) {
if (!QFile::copy(srcItemPath, dstItemPath)) {
return false;
}
} else {
qDebug() << "Unhandled item" << info.filePath() << "in cpDir";
}
}
return true;
}
I'm having trouble compiling a qt project using msvc2012. For some reason, it says that there is an unresolved symbol that equates to a QString function, which I can't understand.
Here's my .pro file ( this program is commandline only, only using qt for convenience
QT += core gui widgets
TARGET = klc2abuspro
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
key.cpp \
klayout.cpp \
deadkey.cpp
HEADERS += \
key.h \
klayout.h \
deadkey.h
OTHER_FILES +=
and here is where the linker issue refers to:
{
QString file;
if(argc < 2)
{
qDebug() << "No file specified. Defaulting to russian.klc";
file = "russian.klc";
}
else
file = argv[1];
QFile input(file);
if(!input.open(QIODevice::ReadOnly | QIODevice::Text))
qDebug() << "File could not be opened";
QTextStream in(&input);
QString str;
KLayout * layout = new KLayout(file.split(".", QString::SkipEmptyParts)[0]);
while(!in.atEnd() && !(str = in.readLine()).contains("LAYOUT"));
in.readLine(); in.readLine(); in.readLine();in.readLine();
bool currChunk = true;
while(currChunk)
{
str = in.readLine();
if(str == "")
{
currChunk = false;
break;
}
QStringList parts = str.split("\t",QString::SkipEmptyParts );
layout->addKey(new Key(parts[0].toUInt(0,16),parts[3], parts[4]));
}
input.close();
//Starting deadkey finder
if(!input.open(QIODevice::ReadOnly | QIODevice::Text))
return -1;
QTextStream pass(&input);
while(!pass.atEnd() && !(str = pass.readLine()).contains("KEYNAME_DEAD"));
pass.readLine();
DeadKey * dkeys[10];
int i = 0;
while((str = pass.readLine()) != "") {
//qDebug() << "Line: " << str;
QStringList parts = str.split("\t",QString::SkipEmptyParts );
//1 is the name, 0 is the unicode value of the character
layout->addDeadKey(dkeys[i] = new DeadKey(parts[1], parts[0]));
i++;
}
//qDebug() << layout->printDeadKeys();
input.close();
// Find deadkey modifiers
bool cont = true;
i = 0;
input.open(QIODevice::ReadOnly | QIODevice::Text);
do {
while(!pass.atEnd() && !(str = pass.readLine()).contains("DEADKEY") && !(str.contains("KEYNAME")));
if(str.contains("KEYNAME")) {
cont = false;
break;
}
pass.readLine();
while((str = pass.readLine()) != "") {
//qDebug() << "Line: " << str;
QStringList parts = str.split("\t",QString::SkipEmptyParts );
//1 is the name, 0 is the unicode value of the character
//qDebug() << "Key to modify: " << parts[0] << "key result: " << parts[1];
dkeys[i]->addModifier(QChar(parts[0].toUInt(0,16)), QChar(parts[1].toUInt(0,16)));
}
i++;
}while(cont);
layout->implementModifiers();
//qDebug() <<layout->printMods();
layout->exportToQML(file.replace(".klc",".qml"));
return 0;
}
The linker error
main.obj:-1: error: LNK2019: unresolved external symbol "__declspec(dllimport) public: class QString & __cdecl QString::operator=(class QString &&)" (__imp_??4QString##QEAAAEAV0#$$QEAV0##Z) referenced in function main
It seems that i also met this problem when I build the project with Qtcreator. but when i use the vs2012 to open the ".pro" project and build it. this error will disappear. Maybe you can try this method.
Simple problem, I just can't open/create a file. It's supposed to save some settings in an xml-file to a given path.
I call the method like this:
xmlwriter->write_settings("./settings.xml");
int XmlWriter::write_settings(QString path)
{
qDebug() << "Path is: " + path;
QDomDocument document;
QDomElement root = document.createElement("settings");
document.appendChild(root);
QDomElement node;
node.setAttribute("name", "Its me!");
node.setAttribute("series", "25");
node.setAttribute("PMT", "200");
root.appendChild(node);
QFile file(path);
if(!file.open(QIODevice::ReadWrite, QIODevice::Text))
{
qDebug() << "Opening file failed!";
return 1;
}
else
{
QTextStream stream(&file);
stream << document.toString();
file.close();
qDebug() << "wrote file to " + path;
return 0;
}
}
You don't pass parameters correctly, so you probably invoke a polymorphic version of QFile::open
Try this:
QFile file(path);
if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << "Opening file failed!";
return 1;
}
else
{
QTextStream stream(&file);
stream << document.toString();
file.close();
qDebug() << "wrote file to " + path;
return 0;
}
I am writing a class to parse Itunes Libray File using QXmlQuery and QT-XSLT.
Here's my sample code:
ItunesLibParser::ItunesLibParser()
{
pathToLib = QString("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
}
void ItunesLibParser::createXSLFile(QFile &inFile)
{
if (inFile.exists()) {
inFile.remove();
}
inFile.open(QIODevice::WriteOnly);
QTextStream out(&inFile);
out << QString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out << QString("<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
out << QString("<xsl:output method=\"text\" />");
out << QString("<xsl:template name=\"playlistNames\">");
out << QString("<xsl:value-of select=\"child::integer[preceding-sibling::key[1]='Playlist ID']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("<xsl:value-of select=\"child::string[preceding-sibling::key[1]='Name']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("</xsl:template>");
out << QString("<xsl:template match=\"/\">");
out << QString("<xsl:for-each select=\"plist/dict/array/dict\">");
out << QString("<xsl:call-template name=\"playlistNames\"/>");
out << QString("</xsl:for-each>");
out << QString("</xsl:template>");
out << QString("</xsl:stylesheet>");
inFile.close();
return;
}
void ItunesLibParser::dumpPlayList()
{
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(QUrl(pathToLib));
QFile xslFile("plist.xsl");
createXSLFile(xslFile);
query.setQuery(QUrl("plist.xsl"));
QStringList* outDump = new QStringList();
query.evaluateTo(outDump);
if(outDump != NULL) {
QStringList::iterator iter = (*outDump).begin();
for (; iter != (*outDump).end();
++iter)
//code flow doesn't come here. It means being() == end()
std::cout << (*iter).toLocal8Bit().constData() << std::endl;
}
return;
}
OutDump here doesn't contain data. While in Shell (xmlpatterns-4.7 mystlye.xsl itunes_music_library.xml ), If I run my Query I get proper output.
Is there anything, wrong I am doing while calling it programatically? I checked out plist.xsl is created properly, but my doubt is whether "/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml" this is getting loaded or not? Or there might be another reasons, I am confused. Is there any experts to throw some light onto problem, I will be glad.
Intead from reading from the file, I read the file into buffer and converted that int string as passed to setquery. That solved the problem.
Here's sample code for those who could face similar problem in future.
void ITunesMlibParser::parsePlayListItemXml(int plistId)
{
QXmlQuery xQuery(QXmlQuery::XSLT20);
QFile inFile("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
if (!inFile.open(QIODevice::ReadOnly)) {
return;
}
QByteArray bArray;
while (!inFile.atEnd()) {
bArray += inFile.readLine();
}
QBuffer xOriginalContent(&bArray);
xOriginalContent.open(QBuffer::ReadWrite);
xOriginalContent.reset();
if (xQuery.setFocus(&xOriginalContent))
std::cout << "File Loaded" << std::endl;
//..
//..
}
Thanks
Rakesh
I am using the QJson for parsing. But I am stuck up with some issues. I have used the following code:
void CityBook ::getCityList(QUrl url)
{
//!connect(cityReply, SIGNAL(readyRead()),this, SLOT(httpReadyRead()));
cityGuideNetworkAccessManager = new QNetworkAccessManager(this);
connect(cityGuideNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(httpReadyRead(QNetworkReply*)));
QNetworkRequest cityRequest(url);
cityGuideNetworkAccessManager->get(cityRequest);
}
void CityBook::httpReadyRead(QNetworkReply *reply)
{
QMessageBox::information(this, tr("HTTP"),
tr(reply->readAll()),QMessageBox::NoButton
);
QJson::Parser parser;
bool ok;
const QByteArray &resultbyte = reply->readAll();
qDebug() << resultbyte;
QVariant result1 = parser.parse(reply->readAll(), &ok);
qDebug() << result1;
QVariantList result=parser.parse(resultbyte,&ok).toList();
qDebug()<< result.size();
if (!ok)
{
qFatal("An error occurred during parsing");
exit (1);
}
qDebug() <<"error String"<< parser.errorString();
qDebug() <<"error" <parser.errorLine();
//! QVariantList entries = result["name"].toList();
foreach (QVariant city, result) {
QVariantMap names = city.toMap();
qDebug() << "\t-" << names.value("name");
}
}
The output is:
Starting /Users/QT Developement/CityBook-build-desktop/CityBook.app/Contents/MacOS/CityBook...
""
QVariant(, )
0
error String ""
error 0
The result of the readAll function is an empty byte array. According to documentation this can mean either that no data are available or that an error occurred.