C++ GUI Text Not Displaying - c++

Basically I made a simple program to search a text file for a certain word. However my text file does not display in the textEdit Object it just displays it blank. I properly placed the text file into the resources and everything. I would really appreciate some input.
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include "find.h"
#include "ui_find.h"
Find::Find(QWidget *parent) : QWidget(parent), ui(new Ui::Find)
{
ui->setupUi(this); //sets up user interface
getTextFile();
}
Find::~Find()
{
delete ui;
}
void Find::on_goButton_clicked()
{
QString word = ui->lineEdit->text(); //gets text and stores in word
ui->textEdit->find(word, QTextDocument::FindWholeWords);
}
void Find::getTextFile()
{
QFile myFile(":/textfile.txt"); //what file
myFile.open(QIODevice::ReadOnly); //opens file
QTextStream textStream(&myFile); //convert to stream
QString line = textStream.readAll(); //store into variable
myFile.close(); //close file
ui->textEdit->setPlainText(line); //display text
QTextCursor textCursor = ui->textEdit->textCursor(); //moves cursor into position
textCursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor, 1); //moves cursor into position
}
The application output also has this in red letters QIODevice::read: device not open

Qt Creator's clean rebuild are broken. Just permanently delete the kit specific folder where qmake has kept the project specific makefiles.
Attempt to do build again. rcc will be invoked specific to .qrc files added, that were skipped by older makefile files, as qmake has to give new makefile files now.

I have Qt 5.4 and my code gave the same error, when it was working with MSVC2010 OpenGL as a compiler. I manually added MinGW 32bit to use it as compiler and it worked.
P.S. I have not installed MSVC2013 for my Qt 5.4., and it works sometimes with MSVC2010 OpenGL without error, but not in this case.

Make sure that you added qrc file in project. If you use qrc file as external source, you should register it by call QResource::registerResource("path to file") in main function.

I just solved this with same error/symptoms. The issue was that I did not have a working compiler for my build kit. I ended up having to manually select my Microsoft Visual C++ Compiler 11.0 (x86). I guess it wasn't able to auto-detect it. This seems to be a common error message for new windows users beginning Qt5.

Related

Image is not shown in QGraphicsScene

Description
I wrote following Qt code. And Make executable file for Windows (*.exe). But Image (JPG) is not shown in QGraphicsScene. And I had already checked whether the path to image is correct. In following code, MyQGraphicsScene is derived class inherits QGraphicsScene class.
I compiled same code in macOS. Then, Executable file (ELF) for macOS ran correctly. Image file was shown in its component. I feel starange that source code is same. But the result is different by environment.
Development environment
Windows 10
Qt version : 5.7.0
C++ Compiler : Microsoft Visual C++ Ver.14.0 (MSVC2015)
Source code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QGraphicsRectItem>
#include <QMessageBox>
#include <QIcon>
#include "TrainingData.h"
#include "trainingDataMaker.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QGraphicsItem *curGItem;
QListWidgetItem *listItem;
ui->setupUi(this);
scene = new MyQGraphicsScene(QRectF(0, 0, 400, 400));
ui->graphicsView->setScene(scene);
listItem = new QListWidgetItem();
listItem->setIcon(QIcon("data/000001.jpg"));
ui->imgListWidget->addItem(listItem);
listItem = new QListWidgetItem();
listItem->setIcon(QIcon("data/000276.jpg"));
ui->imgListWidget->addItem(listItem);
ui->imgListWidget->setIconSize(QSize(300,100));
QPixmap pixmap;
QImage img("data/000001.jpg");
QTransform transForm;
pixmap = QPixmap::fromImage(img);
QGraphicsPixmapItem *imgPixmap = new QGraphicsPixmapItem(pixmap);
transForm = QTransform();
transForm.scale(0.1, 0.1);
imgPixmap->setTransform(transForm);
scene->addItem(imgPixmap);
//connect(scene, SIGNAL(changed(const QList<QRectF> &)), imgPixmap, SLOT(chgSize(const QList<QRectF> &)));
}
I compiled same code in macOS. Then, Executable file (ELF) for macOS
ran correctly. Image file was shown in its component. I feel starange
that source code is same. But the result is different by environment.
Since it works under MacOS/X but not under Windows, one likely explanation is that it's a distribution/environmental problem. In particular, perhaps your program can't find Qt's imageformat plugin (e.g. qjpeg4.dll or qjpeg5.dll) under Windows, and that is why the image is not being displayed.
To test that theory, you could copy the qjpeg*.dll plugin file into the same folder as your .exe file, and then re-run your program and see if that makes it behave better. Alternatively, if you don't want to mess with image format plugins, you could convert your .jpg file to another file format that Qt includes native (i.e. non-plugin-based) support for, such as BMP or PNG, and use that instead.
As result, Cause of this issue is my misunderstanding of current directory in case that the application is launched from IDE. Current directory is (a) in following diagram.
Directory structure before
[Output directory is specified in build configuration] - (a)
|- debug - (b)
| |- test.exe // executable file of this application
| |- data
| |-000001.jpg
|- release
Therefore, I should have located "data" directory includes image files in directory (a) as following diagram. I'm feeling strange this specification of IDE. Of course, Current directory is same diretory of exe file in case that application launch directly(Doublu-clicking exe file) .
Directory structure after
[Output directory is specified in build configuration] - (a)
|- debug - (b)
| |- test.exe // executable file of this application
|- release
|- data
|-000001.jpg

QFileDialog: How to open/select file/dir from package in osX

I have googled a lot but dint find any relative solution for my problem.
PROBLEM: I want to open .MTS file and its working find if its available in any directory. But if its in any package then my QFileDialog is not able to look into that package and select those .MTS files.
CODE:
auto filePaths = QFileDialog::getOpenFileNames(this, "Open Video File", lastOpenedPath, "*.MTS;*.mov");
qDebug() << "File Paths " << filePaths;
Now the .MTS files created under AVCHD(Advanced Video Coding High Definition) package default in Sony & Panasonic HD Camera, and I want to import/select that .MTS files.
HINT: QFileDialog is able to import/select those .MTS files in Windows machine, but fail to import/select in mac machine.
Highly appreciated any thoughts.
Thanks.
Well, if I understand what you want to do properly, I'm not sure that it's possible in Qt alone.
It did turn out to be easier than I expected to simply call in to Cocoa and NSOpenPanel to achieve what I think you're looking for.
Sample project is at: https://github.com/NSGod/widgetsOpenFileDialogCocoa
Basically, I renamed mainwindow.cpp to mainwindow.mm, then added an #import <Cocoa/Cocoa.h>:
#import <Cocoa/Cocoa.h>
void MainWindow::on_openFileButton_clicked()
{
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setAllowedFileTypes:[NSArray arrayWithObjects:#"mts", #"mov", nil]];
[openPanel setAllowsMultipleSelection:YES];
[openPanel setTreatsFilePackagesAsDirectories:YES];
[openPanel setTitle:#"Open Video File"];
NSInteger result = [openPanel runModal];
QStringList stringList;
if (result == NSFileHandlingPanelOKButton) {
NSArray *URLs = [openPanel URLs];
NSLog(#"URLs == %#", URLs);
for (NSURL *URL in URLs) {
stringList += QString::fromNSString(URL.path);
}
// do something with stringList
qDebug() << "filePaths == " << stringList;
}
}
Included in the project is a fakeBundle.component directory, which will be treated as a bundle (or "package") by OS X. But by setting treatsFilePackagesAsDirectories to YES, you can have the NSOpenPanel treat it as a directory (which it really is, of course).
Here is an image showing how the Finder treats this fakeBundle.component directory as if it were a single file:
And here in the NSOpenPanel, it's being treated as a directory:
An OSX package is a:
File system directory that is normally displayed to the user by the Finder as if it were a single file. Such a directory may be the top-level of a directory tree of objects stored as files, or it may be other archives of files or objects for various purposes, such as installer packages, or backup archives.
This is akin to an .mst or .msi file on Windows. Just as with OSX packages you would not be able to open your specified file within one of these packages. Your system open dialog is in fact doing you a disservice by allowing you to see into them, as you cannot open said files.
Your work around is to copy the file out of the package externally to the program then open the copy of the file.

QIODevice::read: device not open

Im trying to read from a file and put into to the text edit and it keeps saying QIODevice::read:device not open. The .txt file is in the same location as my .qrc and .cpp file. I was following a step by step guide from online. From my understanding, they changed something when they went from Q4 to Q5. Does anyone have any hint on how I can fix this. thanks
//My findstuff.h
#ifndef FINDSTUFF_H
#define FINDSTUFF_H
#include <QWidget>
namespace Ui {class FindStuff;}
class FindStuff : public QWidget{
Q_OBJECT
public:
explicit FindStuff(QWidget *parent = 0);
~FindStuff();
private slots:
void on_goButton_clicked();
private:
Ui::FindStuff *ui;
void getTextFile();
};
If you're reading from a .qrc resource file you have to run qmake ("Build->Run qmake" in Qt Creator) before it will be available.
You're not passing the absolute path of the file to QFile::open(), and you're not checking the result of opening the file. In your case, it's a failure and open() returns false, but you're ignoring it, instead of fixing the problem (the wrong path) that caused it.
This has zilch to do with Qt 4 -> Qt 5 upgrade, and everything to do with you assuming the wrong thing about the current directory your application happens to find itself with. Generally speaking, the current directory (or working directory) is arbitrary, and platform- and circumstance-specific, and wholly out of your control. Unless the user gives you a filename that's implicitly referenced to the current working directory (e.g. as a relative path given a commandline argument), you must use absolute file paths or things simply won't work.
It can be related to the version of Qt, since Qt5 sometimes doesn't work with MSVC2010.
I have Qt 5.4 and my code gave the same error, when it was working with MSVC2010 OpenGL as a compiler. I manually added MinGW 32bit to use it as compiler and it worked.
P.S. I have not installed MSVC2013 for Qt 5.4., and it works sometimes with MSVC2010 OpenGL without error, but not in this case.
this is mostly the case if you close a file which is not opened - so just remove the close statement for example:
file->close();
just remove it ;)
I had this problem and it turned out Qt Creator hadn't actually added the .qrc file to my project. I'm using Qt Creator 4.1.0 on a Mac and the projects view doesn't always get populated after creating a new project, first requiring a restart of Creator. My version of this problem may relate to that.
It does not have anything to do with Qt version.
Even though your .txt file is in the same directory as your .cpp file, you still need to add the directory. I had the same problem and that simple solution worked well.
Arman Arefi

Cannot open file in resources directory

I've tested every natural iteration that I can imagine right now but still can not successfully open a file with a QFile object. I've also tested placing the file in the ./resources directory and in the directory with the source file.
I've cleaned my project in between each test and restarted Qt Creator as well. I've also deleted my *.pro.user project configuration file and tested with new versions of that.
#include <QFile>
#include <QDebug>
...
//QFile input_file("./resources/testfile.txt");
//QFile input_file("qrc:/10_graph.txt");
//QFile input_file("testfile.txt");
QFile input_file(":/testfile.txt");
if (!input_file.exists()) {
qDebug() << "File does NOT exist";
exit(11);
}
Qt Creator >> About
Qt Creator 3.1.1 (opensource)
Based on Qt 5.2.1 (Clang 5.0 (Apple), 64 bit)
You should add a resource file to your project and add the testfile.txt to the resources. After that you can access the file from resources by :
QFile input_file(":/testfile.txt");
If you add a prefix to the resources it can be accessed by :
QFile file(":/somePrefix/new.txt");
If you put the file in a folder alongside the source directory and add it to the resources, you can access it by :
QFile file(":/folderName/new.txt");

Qt, windows cannot find file that Qt open file dialog can

So I have a Qt program that saves files among other things. I saved a few files in my C:/ directory. When I look for the file in windows explorer, cygwin, or my command prompt, I cannot find the file. I checked my folder options and those look fine. Despite not being able to find the file, when I need to load a file in my Qt program, the program is able to find the file. Only my program is able to find the file, windows cannot. I am logged in as an administrator, but could this possibly have something to do with permissions?
Also, it may be worth noting that when I save files in c:/users/me/Documents/folder/folder I don't seem to have an issue.
Code that saves file:
QString saveFileName = QFileDialog::getSaveFileName(this,"Select the file you wish to save to.","","");
QFile saveFile(saveFileName);
if(saveFile.open(QIODevice::WriteOnly))
{
QTextStream stream(&saveFile);
QString stringToSaveToFile;
stream << stringToSaveToFile;
saveFile.close();
}
else
{
QMessageBox::warning(this, "Error", "Cannot open file.");
}
Code that opens file:
QString selectedFile = QFileDialog::getOpenFileName(this, "Select a .pro file.", "", tr("Profile file (*.pro);;All (*.*)"));
QString fileContents;
QFile file(selectedFile);
if (file.open(QIODevice::ReadOnly) | (QIODevice::Text))
{
QTextStream in(&file);
fileContents = in.readAll();
}
else
{
QMessageBox::warning(this, "Error", "Unable to open file.");
}
Edit: Just tried this on a different computer. My computer has windows 8, the other computer had windows XP. I could not replicate the problem on the XP machine.
Edit:
I believe I have found what the issue is (http://answers.microsoft.com/en-us/windows/forum/windows_vista-files/windows-explorer-compatibility-files/5b377209-cfe4-4be6-959d-e1de4b8be16d), but I am still trying to find out how to resolve it.
The files I am trying to save to the c:/ directory are actually being saved in C:/users/username/AppData/Local/VirtualStore.
Is there a way to somehow override this?
For now my solution is to warn the user if they save in the C:/, C:/Program Files/, C:/Program Files (x86), or C:/Windows/ directories. All files saved in these directories actually get saved in C:/User/Current User/AppData/Local/VirtualStore/.
If anyone has a better solution let me know.
Even though you might be logged in as an administrator by default most programs are run in unelevated mode (basically, NOT as an administrator). Also by default unelevated programs do not have write access to the root directory on C: drive (same way they do not have permission to write in, for example, C:\Program Files\). This was not always the case - I do not remember exactly at the moment but I think write to program files was already protected in Windows XP, and C: became protected only afterwards, I think at least since Windows 7? Anyway, for compatibility reasons write to those protected directories is virtualized.
Try running your Qt application in elevated mode (right click -> Run as administrator, or right click -> Properties -> Compatibility -> Run this program as an administrator) if you want to write directly in C:\, but really, you shouldn't.
If you are really worried about users being confused by this, you can implement a check for write access - after user chooses location for the file, but before an actual write - and display a warning or let them choose another location.