QDesktopServices::openUrl with selecting specified file in explorer - qt

In most coding programs, you can right click on the item and click show in explorer and it shows the file in explorer with the item selected. How would you do that in Qt with QDesktopServices? (or any way to do it in QT)

you can use this method to select file on Windows or MacOS ,if you want select on linux you can find a way in QtCreator sources.
void select(const QString& path){
#if defined(Q_OS_WIN)
const QString explorer = "explorer";
QStringList param;
if (!QFileInfo(path).isDir())
param << QLatin1String("/select,");
param << QDir::toNativeSeparators(path);
QProcess::startDetached(explorer, param);
#elif defined(Q_OS_MAC)
QStringList scriptArgs;
scriptArgs << QLatin1String("-e")
<< QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
.arg(path);
QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
scriptArgs.clear();
scriptArgs << QLatin1String("-e")
<< QLatin1String("tell application \"Finder\" to activate");
QProcess::execute("/usr/bin/osascript", scriptArgs);

Have you tried using the file:/// syntax? The following is taken from a code base I'm working with:
PyQt4.QtGui.QDesktopServices.openUrl(PyQt4.QtCore.QUrl('file:///%s' % dirname))

Related

Overwrite an existing file using Qt

I'm trying to overwrite an existing file using Qt. Since QFileDialog::getSaveFileName will always replace the selected file if it already exists, I've tried creating a custom QFileDialog in over to get to my goal so I used what has been suggested in this link but it seems not to work...
What I've tried so far:
QFileDialog diag(this);
diag.setFileMode(QFileDialog::AnyFile);
diag.setNameFilter(tr("Test (*.tst)"));
diag.setAcceptMode(QFileDialog::AcceptSave);
diag.exec();
QStringList namefile = diag.selectedFiles();
QFile file(namefile[0]);
if(file.open(QIODevice::WriteOnly | QIODevice::Text)){
QTextStream stream(&file);
stream << ui->lineEdit->text() << endl;
}
file.close();
result:

How to work around string splitting while loading a list from a file in QT

I'm trying to create a simple "To Do list" app in QT Creator while coding the part that loads and saves the list from a file I get stuck on a problem.
If you enter a string like "Do my homework" the program threads the string as it should, but when you load the program again the save file got split in words. So it gets all the entries but each word separated ("Do", "my", "homework").
What is the solution? I tried working with 'char arrays' and 'getline' but they give me nothing but errors.
Here is my code for the save and load parts:
void MainWindow::LoadList(){
std::ifstream load_file("./data.bin");
char loader[255];
while (load_file >> loader){
QString Writer = QString::fromStdString(loader);
ui->lstTaskList->addItem(Writer);
}
}
void MainWindow::SaveList(){
std::ofstream save_file("./data.bin");
for (auto i = 0; i < ui->lstTaskList->count(); i++){
QString Saver = ui->lstTaskList->item(i)->text();
std::string saver = Saver.toStdString();
save_file << saver << std::endl;
}
}
Can anyone help me with this, please?
My thanks in advance...
The anwser was using QFile and QByteArray for me, I knew about QFile but it tries using basic "std" c++ till I learned more about QT.

How do I select a row in a QTreeview programatically?

Update: Let me try to simplify the issue and steps. Does anyone see where I've gone wrong? Also, this is on OSX 10.7.5/Qt 5.1 – perhaps it is an OSX issue?
I pass an absolute path which points to a directory of images and set the root path of my QFileSystemModel instance and use the index returned by that to set my QTreeView instance root index
QModelIndex idx = dirmodel->setRootPath(dPath);
myTreeView->setRootIndex(idx);
I then set the current index of the treeview to that index. Which I guess is pointing to the directory – perhaps this is wrong?
myTreeView->setCurrentIndex(idx);
I have tried using the selectionModel of the treeView to make the selection using that index:
myTreeView->selectionModel()->select(idx,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
I have also tried accessing a child of the directory and using that to set the current index and selection:
QModelIndex next_index =myTreeView->currentIndex().child(1,0);
But I still am not getting the selection on my treeview.
Context: For a Qt learning project I am building an image viewer. I have a 'QTreeView' with a backing 'QFileSystemModel.' The user has the option to select a directory of images and only the contents of that directory will be displayed in the QTreeView (i.e. it is not displaying the entire file system, just the subdirectory the user selects).
I would like to have the first item in the QTreeView selected when the user changes directories. I have seen this question (Selecting a row in QTreeView programatically) but it didn't work for me. I've been poking at this for a few hours now. What am I doing wrong? I am able to select directories and display the images but I am missing how to set the QTreeView selection.
My code is below, with various attempts commented out. The console output from the qDebug statement is always:
next_index -1 -1
void DirBrowser::on_actionSet_Image_Directory_triggered()
{
QString dPath = QFileDialog::getExistingDirectory(this,
tr("Set Image Drectory"), QDir::currentPath());
if (!dPath.isEmpty()) {
QModelIndex idx = dirmodel->setRootPath(dPath);
myTreeView->setRootIndex(idx);
myTreeView->setCurrentIndex(idx);
QModelIndex next_index =myTreeView->currentIndex().sibling(1,0);
//QModelIndex next_index = myTreeView->model()->index(1, 0);
//QModelIndex next_index =idx.child(0,0);
qDebug() << "next_index" << next_index.row() << next_index.column();
//myTreeView->setCurrentIndex(next_index);
myTreeView->selectionModel()->select(next_index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
QString path = dirmodel->fileInfo(next_index).absoluteFilePath();
qDebug() << "set Dir" << path;
}
}
Figured it out. The problem was that I was trying to make a selection on the QTreeView before the specified directory had finished being loaded. In other words, tryng to make the selection within the method where I was changing directories.
The solution is to listen for the directoryLoaded(QString) SIGNAL that QFileSystemModel emits.
void QFileSystemModel::directoryLoaded ( const QString & path ) [signal]
This signal is emitted when the gatherer thread has finished to load the path.
This function was introduced in Qt 4.7.
connect(dirmodel,
SIGNAL(directoryLoaded(QString)),
this,
SLOT(model_directoryLoaded(QString)));

Segmentation fault on QPixmap::load

This is the code:
void MainWindow::setPic(QString loc, int panel)
{
if(panel == 1)
{
loc1 = loc;
QPixmap pmap;
facedetect(loc1.toStdString(), 1, "CAND1.jpg");
qDebug() << "Loading : " << loc1;
pmap.load(loc1); // I'm getting the segfault error in this line
qDebug() << "Loaded : " << loc1;
ui->PicView1->setPixmap(pmap);
}
}
How could I resolve this error?
BTW, I'm using Qt 4.8 with the latest Qt Creator, on Ubuntu 12.04.
I tried it with wallpapers, it crashes. I tried it with my 1x1 id pic, crashed (how rude...), I tried it with a strip of my examination schedule (cropped from a different image), it said it loaded, but the QLabel PicView1 doesn't display anything.
I tried declaring the QPixmap as global variable, got segfault.
Don't fill you image with white before loading...
Use QPixmap hence :
QString loc;
// fill loc with a path to your image file.
QPixmap pmap;
pmap.load(loc);
Be carefull, all image type can't be read with QT. Look here QtImageReading to see the datatype supported by QT.

QFileSystemModel and QFileSystemWatcher delete from disk

I have a QTreeView which is populated through a reimplementation of QFileSystemModel. As far as I know, QFileSystemModel installs a QFileSystemWatcher on the rootPath. What I'm trying to do is notify in my program when a file is being deleted directicly on the rootPath but i havent found any signal o reimplemented function which provides me that information.
My application upload some files thrugh an ftp connection and when the file is fully uploaded i remove it from the location, so i want a notification from the reimplementation of QFileSystemModel when the file is deleted directicly (not from the remove method or something similar).
I Hope you can help me. I have searched a lot on the web but I cant find anything.
Cheers.
You can use the FileSystemModel's rowsAboutToBeRemoved signal (inherited from QAbstractItemModel).
It will be fired whenever a row is removed from the model. The parent, start and end parameters allow you to get to the filename (in column 0 of the children).
Sample code:
// once you have your model set up:
...
QObject::connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)),
receiver, SLOT(toBeRemoved(const QModelIndex&, int, int)));
...
// in receiver class:
public slots:
void toBeRemoved(const QModelIndex &parent, int start, int end) {
std::cout << start << " -> " << end << std::endl;
std::cout << parent.child(start, 0).data().typeName() << std::endl;
std::cout << qPrintable(parent.child(start, 0).data().toString()) << std::endl;
}
(Using std::cout isn't good practice with Qt I think, this is just to get you started.)
The other aboutToBe... signals from QAbstractItemModel can be used for the other events that happen on the filesystem.

Resources