On QTreeView double_Clicked event: how to know which folder was clicked? - c++

I'm still pretty new to C++ and qt creator. I have a TreeView displaying a directory, and upon double-clicking a folder I'd like to be able to get the directory of the folder, so i can do something with the contents. I notice the double_Clicked event passing along a "const QModelIndex& index" and I suppose this holds some information on which folder of the tree was clicked. I can't find any documentation on this signal, and what the "index" passed along could be. Does anyone have an explanation, tutorial, example, documentation, ... for me? I've been searching for awhile and trying things out but I can't find the solution. Or additionally: how can I check what gets passed along? How could I print this, or know what it is?

You can set up your treeView in the constructor like this:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QFileSystemModel(this);
model->setRootPath("");
ui->treeView->setModel(model);
ui->treeView->setRootIndex(model->index("/home/waqar/"));
}
And in the double_Clicked() slot, use the QModelIndex to get the name of the folder you clicked on:
void MainWindow::on_treeView_doubleClicked(const QModelIndex &index)
{
//displays the name of the folder you clicked on in the terminal
qDebug () << index.data(Qt::DisplayRole).toString();
//get full path
QString path = model->filePath(index)
}

Related

QtListWidgetItem with Pixmap crashes if to many

I'm a noob, so sorry if my question feels dumb.
I use Qt Creator to make a kind of image viewer.
I added a QListWidget and added items with a pixmap. So far, so good.
Now I try to read the hole directory and add all 438 images.
The app crashes with this message:
Cn::Process::NotifyOutOfMemory(). 17:47:36: The program has
unexpectedly finished. 17:47:36: The process was ended forcefully.
If I reduce the count to 85. The app opens, but does only show 77 images.
I tried to fix this by changing addItem to addItems but don't know how to get the QListWidgetItem in a QList or on any other way. And than it is the question of this is a solution.
Can someone give me a kick in the right direction?
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QDir dir("C:/");
QStringList items; // String???
foreach(QFileInfo var, dir.entryInfoList ()){
if(var.isFile ()){
//items += // What to do here ??
ui->listWidget->addItem (new QListWidgetItem(QPixmap(var.absoluteFilePath ()), var.fileName ()));
}
ui->listWidget->addItems (items);
}
}
Michael

How to get names of files from a folder and add them to a tree widget as children in qt

I am making a program that needs to be able to output the names of files from a specific folder as items in a Tree Widget but I cannot seem to figure it out. I managed to do it in a list widget without too much hassle but I cant get that code to work with a tree widget. Below is the code I wrote to get the described functionality with a list widget
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QString path = "C:/Program Files/GUI_Project/bin";
QDir dir(path);
if (!dir.exists())
{
dir.mkpath(path);
}
QDir myPath(path);
myPath.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
MyList = myPath.entryList();
ui->listWidget->addItems(MyList);
}
Another option is to use a QFileSystemModel and use setRootPath("your/path") to create a model of a folder. You can use setFilter() to decide what is shown Filter List.Then you can add that model to a QTreeView. It's just like a QTreeWidget except it has much better performance and is the better option for most use cases imo. For example, if a file gets added or deleted from that directory, the model will change and update in your program. A QTreeWidget can't do that.
QFileSystemModel *dirModel = new QFileSystemModel(); //Create new model
dirModel->setRootPath("C:/Program Files/GUI_Project/bin"); //Set model path
dirModel->setFilter(QDir::Files); //Only show files
ui->treeView->setModel(dirModel); //Add model to QTreeView
QModelIndex idx = dirModel->index("C:/Program Files/GUI_Project/bin"); //Set the root item
ui->treeView->setRootIndex(idx);
If you want to stick with a QTreeWidget however, you will have to recursively iterate over a folders contents and add each item individually.
You simply iterate over your input list and create a QTreeWidgetItem object for each entry.
If you pass the tree widget as the parent it will become a top level item in the tree, if you pass another tree widget item as the parent, it becomes a child entry of that item.

How to download files from QWebView?

I created a small web browser with QT Creator and QWebView. I's working very good and the pages are loading very fast. But how can I make my browser capable of downloading files? I looked through the signals and functions list, but I did't find something that could help me.
How can I found out if a QUrl contains a link to a file other than text/html so I can download it?
QWebView has a 'QWebPage' member which you can access it's pointer with webView.page() . This is where you should look. QWebPage has two signals: downloadRequested(..) and unsupportedContent(..). I believe dowloadRequest is only emitted when user right clicks a link and selects 'Save Link' and unsupportedContent is emitted when target URL cannot be shown (not an html/text).
But for unsupportedContent to be emitted, you should set forwardUnsupportedContent to True with function webPage.setForwardUnsupportedContent(true). Here is a minimal example I have created:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->webView->page()->setForwardUnsupportedContent(true);
connect(ui->webView->page(),SIGNAL(downloadRequested(QNetworkRequest)),this,SLOT(download(QNetworkRequest)));
connect(ui->webView->page(),SIGNAL(unsupportedContent(QNetworkReply*)),this,SLOT(unsupportedContent(QNetworkReply*)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::download(const QNetworkRequest &request){
qDebug()<<"Download Requested: "<<request.url();
}
void MainWindow::unsupportedContent(QNetworkReply * reply){
qDebug()<<"Unsupported Content: "<<reply->url();
}
Remember, MainWindow::download(..) and MainWindow::unsupportedContent(..) are SLOTs !

Qt: Change icon in a QFileInfo object

My foremost question is:
How do I set/change the file icon in a QFileInfo object?
If you look at my code, Qlist<QFileInfo> lists the icon of all my folders in my home directory as gnome-fs-directory. Which means, QFileInfo lists even my desktop folder's icon as plain gnome-fs-directory.
But I want Desktop to have QFileIconProvider::Desktop as icon.
Which consequently leads to the 2nd question:
Is QFileInfo the appropriate class to use to find out the icon that QFileSystemModel would use?
Which leads to the 3rd question:
Why did my QDir not pass QFileSystemModel a QFileInfo list with the appropriate icon role for Desktop?
So the ultimate question is, what do I have to do to ensure QFileSystemModel uses the appropriate icon role, when listing itself in a tree view or list view?
Code to find out the file icon of each folder in the home folder:
void MainWindow::fileIconInfo(QFileSystemModel *model)
{
QFileIconProvider *iconprov = model->iconProvider();
QFileInfoList fileInfoList = QDir::home().entryInfoList();
QFileInfoList::Iterator i;
foreach (QFileInfo fi, fileInfoList){
if (fi.fileName() == QString("Desktop"))
/*change the icon to QFileIconProvider::Desktop*/;
//the following line indicates all my icons are gnome-fs-directory!!*/
std::cout << iconprov->icon(fi).name().toStdString() << std::endl;
}
}
This is my main window:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
fileSystemTree(ui->listView);
fileSystemTree(ui->treeView);
}
Setting the model for the view:
void MainWindow::fileSystemTree(QAbstractItemView *view) {
QFileSystemModel *model = new QFileSystemModel;
model->setRootPath(QDir::homePath());
view->setModel(model);
view->setRootIndex(model->index(QDir::homePath()));
fileIconInfo(model);
}
I think what you are describing is caused by the fact that QFileIconProvider is detecting that you use Gnome, and the is using Gtk style - no matter what. Could you try to start some other desktop environment and see if problem remains? If it does then I am right and only thing you can do is to subclass QFileSystemModel and change QIcon returned from data method - but this is quite crude and non-flexible solution.

setCentralWidget() causing the QMainWindow to crash.. Why?

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
this->setupUi(this);
this->setupActions();
this->setWindowTitle(tr("CuteEdit"));
label = new QLabel(tr("No Open Files"));
this->setCentralWidget(label);
label->setAlignment(Qt::AlignCenter);
}
By above code, I get a GUI like this(Its a screenshot of whole screen, Only observe the window displayed in middle of page of ebook). (I used QT Designer)
Now, i want user to select File->Open.. A Dialog appears and file gets selected.. Its contents are to be displayed in *textEdit widget..
Function for that is below..
void MainWindow::loadFile()
{
QString filename = QFileDialog::getOpenFileName(this);
QFile file(filename);
if (file.open(QIODevice::ReadOnly|QIODevice::Text))
{
label->hide();
textEdit->setPlainText(file.readAll());
mFilePath = filename;
QMainWindow::statusBar()->showMessage(tr("File successfully loaded."), 3000);
}
}
The window crashes at line:-
textEdit->setPlainText(file.readAll());
But if i comment the line:-
this->setCentralWidget(label);
i mean i remove label as being the central widget, the program runs as expected.. Why?
And also, I am not clear about the concept of CentralWidget. Pls guide.
JimDaniel is right in his last edit. Take a look at the source code of setCentralWidget():
void QMainWindow::setCentralWidget(QWidget *widget)
{
Q_D(QMainWindow);
if (d->layout->centralWidget() && d->layout->centralWidget() != widget) {
d->layout->centralWidget()->hide();
d->layout->centralWidget()->deleteLater();
}
d->layout->setCentralWidget(widget);
}
Do you see that if your MainWindow already had centralWidget() Qt schedules this object for deletion by deleteLater()?
And centralWidget() is the root widget for all layouts and other widgets in QMainWindow. Not the widget which is centered on window. So each QMainWindow produced by master in Qt Creator already has this root widget. (Take a look at your ui_mainwindow.h as JimDaniel proposed and you will see).
And you schedule this root widget for deletion in your window constructor! Nonsense! =)
I think for you it's a good idea to start new year by reading some book on Qt. =)
Happy New Year!
Are you sure it's not label->hide() that's crashing the app? Perhaps Qt doesn't like you hiding the central widget. I use Qt but I don't mess with QMainWindow that often.
EDIT: I compiled your code. I can help you a bit. Not sure what the ultimate reason is as I don't use the form generator, but you probably shouldn't be resetting the central widget to your label, as it's also set by the designer, if you open the ui_mainwindow.h file and look in setupGui() you can see that it has a widget called centralWidget that's already set. Since you have used the designer for your GUI, I would use it all the way and put the label widget in there as well. That will likely fix your problems. Maybe someone else can be of more help...
I'm not sure I understood your problem, neither what the guys above said (which I guess are valid information) and it seems to be an old topic.
However, I think I had a problem that looks like this and solved it, so I want to contribute my solution in case it helps anyone.
I was trying to "reset" central widget using QLabels. I had three different ones, switch from first to second, then to third and failed to switch back to the first one.
This is my solution that worked:
Header file
QLabel *imageLabel;
Constructor
imageLabel = new QLabel("<img src='/folder/etc.jpg' />");
this->setCentralWidget(imageLabel);
Reset
imageLabel = NULL;
imageLabel = new QLabel("<img src='/folder/etc.jpg' />");
this->setCentralWidget(imageLabel);
Hope that helps
Aris