Modifying QFileDialog::getOpenFileName to have an additional drop down - c++

I am a student programmer using Qt to build a reader Table for my company. This reader is both an editor and converter. It reads in a .i file allows table editing of a text document and then puts out a .scf file which is essentially a separated value file stacked under a legend built with headers. I digress... Basically the file format imported is really hard to scan and read in(mostly impossible) so what I'd like to is modify the open file preBuilt QFileDialog to include an additional drop down when older file types are selected to declare their template headers.
When the user selects .i extension files(option 2 file type) I would like to enable an additional drop down menu to allow the user to select which type of .i file it is(template selected). This way I don't have to deal with god knows how many hours trying to figure out a way to index all the headers into the table for each different type. Currently my importFile function calls the dialog using this:
QString fileLocation = QFileDialog::getOpenFileName(this,("Open File"), "", ("Simulation Configuration File(*.scf);;Input Files(*.prp *.sze *.i *.I *.tab *.inp *.tbl)")); //launches File Selector
I have been referencing QFileDialog Documentation to try and find a solution to what I need but have had no avail. Thanks for reading my post and thanks in advance for any direction you can give on this.
UPDATE MAR 16 2012;
First I'd like to give thanks to Masci for his initial support in this matter. Below is the connect statement that I have along with the error I receive.
//Declared data type
QFileDialog openFile;
QComboBox comboBoxTemplateSelector;
connect(openFile, SIGNAL(currentChanged(const &QString)), this, SLOT(checkTemplateSelected()));
openFile.layout()->addWidget(comboBoxTemplateSelector);
I also noticed that it didn't like the way I added the QComboBox to the modified dialog's layout(which is the second error). I really hope that I'm just doing something dumb here and its an easy task to overcome.
In response to tmpearce's comment heres my header code;
#include <QWidget>
namespace Ui {
class ReaderTable;
}
class ReaderTable : public QWidget
{
Q_OBJECT
public:
explicit ReaderTable(QWidget *parent = 0);
~ReaderTable();
public slots:
void checkTemplateSelected();
void importFile();
void saveFile();
private:
Ui::ReaderTable *ui;
};
Thanks for reading and thanks in advance for any contributions to this challenge!

Instance a QFileDialog (do not call getOpenFileName static method), access its layout and add a disabled QComboBox to it.
// mydialog_ and cb_ could be private fields inside MyClass
mydialog_ = new QFileDialog;
cb_ = new QComboBox;
cb_->setEnabled(false);
connect(mydialog, SIGNAL(currentChanged(const QString&)), this, SLOT(checkFilter(const QString&)));
mydialog_->layout()->addWidget(cb_);
if (mydialog_->exec() == QDialog::Accepted) {
QString selectedFile = mydialog_->selectedFiles()[0];
QString cbSelection = cb_->currentText();
}
the slot would be something like:
void MyClass::checkFilter(const QString& filter)
{
cb_->setEnabled(filter == "what_you_want");
}
returning from the dialog exec(), you could retrieve selected file and cb_ current selection.
Notice you could add something more complex than a simple QComboBox at the bottom of the dialog, taking care of gui cosmetics.
Actually I don't like very much this approach (but that was what you asked for :-). I would make a simple dialog like this:
and enable the combo only if the selected file meets your criteria. The "browse" button could call getOpenFileMethod static method in QFileDialog.

You can handle item selection by this signal:
void QFileDialog::fileSelected ( const QString & file )
Then it occurs, call setFilter with type you want.
Sorry, if i don't understand your task.

Related

How to add hyperlinks in Qt without QLabel?

I have some labels and layouts nested inside a QWidget to build a part of a sidebar. Each QWidget is its own section and one component currently looks like this:
To my understanding, you can only set hyperlinks with QLabel, but I'm trying to get the whole area between the white lines clickable. This is including the icon and the whitespace. Is there any way to achieve this?
This got marked as a duplicate to the opposite of what I was asking, so I'd like to reiterate that I'm trying to implement a hyperlink without QLabel.
You can easily have a widget open a link on click:
class Link : public QWidget {
Q_OBJECT
public:
Link(QUrl url, QWidget p = nullptr) : QWidget(p), _url(url) {}
QUrl _url;
void mouseReleaseEvent(QMouseEvent *) { QDesktopServices::openUrl(_url); }
}
You can avoid any extra signals and connections, and have each link widget store its own link internally, the url can be set on construction and changed at any time. Not using signals and slots makes it easier to change the link too, without having to disconnect previous connections.
IMO going for a signals and slots solution is only justified when you want different arbitrary behavior. In this case you always want the same - to open a particular link, so you might as well hardcode that and go for an easier and more computationally efficient solution.
I would just manually catch the SIGNAL for clicked() and use desktop services to open the url in code.
bool QDesktopServices::openUrl ( const QUrl & url ) [static]
Opens the given url in the appropriate Web browser for the user's desktop environment, and returns true if successful; otherwise returns false.
http://doc.qt.io/qt-4.8/signalsandslots.html
Using this type of syntax, or in the designer, you can also connect a signal to a slot.
connect(widgetThatRepresentsURL, SIGNAL(clicked()),
handlerThatWillOpenTheURL, SLOT(clicked_on_url()));
For widgets that don't have a signal set up for clicked (or whatever event you are interested in), you can subclass the widget in question and reimplement...
void QWidget::mousePressEvent ( QMouseEvent * event ) [virtual protected]
Specifically for creating a signal, there is emit. I've used this in the past like the following
void Cell::focusInEvent(QFocusEvent *e)
{
emit focus(this, true);
QLineEdit::focusInEvent(e);
}
with the following in the header
signals:
void focus(Cell *, bool);

Create Droppable file link in Windows from QTableWidget row/cell Drag

I would like to allow the user to drag a file path from a QTableWidget cell and drop this in a file manager (e.g. Windows Explorer) to create a link (Windows file shortcut).
I assume this requires modifying the dragged object data in place?
To start with, I have tried subclassing QTableWidget to reimplement the events
#include <QTableWidget>
#include <QEvent>
class tableWidget : public QTableWidget
{
Q_OBJECT
public:
tableWidget(QWidget *parent = 0);
~tableWidget();
protected:
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dragLeaveEvent(QDragLeaveEvent *event);
void dropEvent(QDropEvent *event);
};
and "promoted" QTableWidget in Qt Designer to my tableWidget (be sure not to have the objectName identical to the class) and set dragEnabledto true.
However, the event handlers seem not to be executed.
So I thought I might be looking in the wrong place, but QTableWidgetItem does not appear to have Drag and Drop events implemented, although its documentation says
By default, items are enabled, editable, selectable, checkable, and can be used both as the source of a drag and drop operation and as a drop target.
What do I need to do in order to create this behaviour? Is it necessary to create a QDrag object manually as shown in Drag and Drop?
To answer my own question: Yes - it seems that installing an object with eventFilter method allows handling the widget's viewport()'s QMouseEvent's, where a QDrag object is set up according to the documentation linked in the question.
Then use
QTableWidgetItem *twi = ui->tWidget->itemAt( mouseEvent->pos() );
QString dirname( twi->text() );
to retrieve the dragged table cell data
However, passing the link file contents in QDrag object MIME data does not seem to work, as also noted here. Instead, passing the url ("file:///...") of an existing .lnk file works with Windows Explorer.
This does not really make a difference, as the link file needs to be created with e.g. QFile::link() anyway. Remove it after operation is completed.
While several Mime data segments can be passed (see Qt\Examples\Qt-5.5\widgets\draganddrop\dropsite) I have not yet figured out what the order of preference is - e.g. the target application uses either the plain text target path or the reference url to the link file.
When using right mouse button for a drag-n-drop action, a context menu will be shown on release, depending on the DropActions specified as supportedActions in exec(). The dropAction returned by exec then might also be TargetMoveAction and IgnoreAction. Not sure if the context menu can be disabled.

QT - Dialog(modal) with sub functions

firstly I have to apologize for my bad English, I'm still learning the language ;)
Now, my Problem:
I've created a Dialog named form.ui, I've created it via pointer in the main Header:
private:
QDialog *newform;
Ui::Form Form;
private slots:
void slotShowEntry();
void newEntry();
Then I called it in the main Program:
void SoftwareV::slotNewEntry()
{
newform =new QDialog;
newform->setModal(true);
Form.setupUi(newform);
newform->show();
connect(Form.buttonBox_ok_ab, SIGNAL(accepted()), newform, SLOT(newEntry()));
}
Now, I want to get the information the user has written/given into the Dialog with the Subfunction called newEntry(),eg I want to get text from the QLineEdit, but I have no idea how I can connect the Dialog with the subfunction.
I hope somebody can help me with this Problem! thank you!
There's not quite enough information in your code to be exact, but I think what you're looking for is something like this in your newEntry method:
QString user_text = Form.someLineEdit->text ();
Instead of "someLineEdit", the name of the control is the name you gave it in Qt Designer when you created the form. What you do with the user_text result is up to you. Each control in the form has a unique name, and how you get data out of the control depends on the type of control (QCheckBox, QComboBox, QLineEdit, etc.). Each of those controls has functions for setting and retrieving data. You can look them up in Qt Assistant for complete details.

Close QFileDialog only when click "open"

Whenever I select a file in my QFileDialog the accepted signal is fired and the window closes. I want to keep the window open so I can select multiple files and then capture the signal fired when "open" is clicked.
QFileDialog* myDialog = new QFileDialog(this);
myDialog->setFileMode(QFileDialog::ExistingFiles);
myDialog->setVisible(true);
What signals should I be connecting here to achieve this effect?
The QFileDialog::ExistingFiles should guarantee that multiple files can be selected. Given that, you can connect to the signal:
void QFileDialog::filesSelected(const QStringList & selected)
Directly from the documentation:
When the selection changes for local operations and the dialog is accepted, this signal is emitted with the (possibly empty) list of selected files.
However, if you are only interested in collecting such files, you can totally avoid signal-slot and write (taken again from the documentation):
QStringList fileNames;
if (dialog.exec())
fileNames = dialog.selectedFiles();
Note that in this case dialog object has been created on the stack (which is the common approach for such objects).
Your code looks fine to me. I believe you are double clicking on the file inside the dialog instead of holding on the Ctrl and single clicking on all the files you need.
You can optionally use an event filter and ignore the double click event.
Once you click on Open, you can get a list of all the file paths in the QStringList given by QFileDialog::selectedFiles(). Also it's better to use a stack variable here and use exec method to launch it as pointed out by BaCaRoZzo.
QFileDialog myDialog(this);
myDialog.setFileMode(QFileDialog::ExistingFiles);
if(myDialog.exec())
{
qDebug() << myDialog.selectedFiles();
}
Whenever I select a file in my QFileDialog the accepted signal is fired and the window closes. I want to keep the window open so I can select multiple files
All other answers is just solution for selection many files one time and CLOSE window after Open button pressing. Get my solution, it is not very simple because it required lot of work:
I used lamda expressions and new signals and slots syntax in my answer, but you can use old syntax or add
CONFIG += c++11
to the .pro file and use lambdas.
Subclass QFileDialog:
Header:
#ifndef CUSTOMFILEDIALOG_H
#define CUSTOMFILEDIALOG_H
#include <QFileDialog>
#include <QDebug>
class CustomFileDialog : public QFileDialog
{
Q_OBJECT
public:
explicit CustomFileDialog(QWidget *parent = 0);
void setDefaultGeo(QRect);
signals:
void newPathAvailable(QStringList list);
public slots:
private:
bool openClicked;
QRect geo;
};
#endif // CUSTOMFILEDIALOG_H
When you click open, you hide your dialog, not close! Cpp:
#include "customfiledialog.h"
CustomFileDialog::CustomFileDialog(QWidget *parent) :
QFileDialog(parent)
{
openClicked = false;
connect(this,&QFileDialog::accepted,[=]() {
openClicked = true;
qDebug() << openClicked;
this->setGeometry(geo);
this->show();
emit newPathAvailable(this->selectedFiles());
});
}
void CustomFileDialog::setDefaultGeo(QRect rect)
{
geo = rect;
}
Usage:
CustomFileDialog *dialog = new CustomFileDialog;
QStringList fileNames;
dialog->setFileMode(QFileDialog::ExistingFiles);
dialog->show();
dialog->setDefaultGeo(dialog->geometry());
connect(dialog,&CustomFileDialog::newPathAvailable,[=](QStringList path) {
qDebug() << path;
});
Why do you need setDefaultGeo? Without this method, your window will move after Open pressing.
What we get?
I open filedialog and select two files:
I clicked Open, but window didn't close! You can choose new files again and again!
One more file and so on:
Window will closed only when user press Close button, but you will have all path which user choose.
As you said:
I want to keep the window open so I can select multiple files
You get this.
I don't think anyone has understood the question (or it could be just me looking for my own solution)...
I had the same issue. As soon as I clicked a file the dialog would close. I couldn't ever select a file and then click "Open" because the dialog instantly closed as soon as I single clicked a file.
related: qtcentre.org/threads/48782-QFileDialog-single-click-only
It turns out it was my linux os settings (under mouse). File opening was set to single-click. I still feel like something external might have toggled this but that is just speculation. It appears Qt was going the right thing. Check another application, like kate on KDE and see if it has the same behavior. That is what clued me in to the source of my issue.

qt5 designer, using fileopen, displaying file path in lineedit, is there an issue doing it this way?

just started using qt,
looked through docs, google, examples, etc.. trying to find simple examples(working mind you)
that showed how to do (imho) simple things, by themselves.
well i stumbled upon my answer and i was wondering if this approach would cause an issue later as the code becomes more complex.
there are more includes than needed for this example, but this is direct from working code.
mainwindow.h:
i added
private slots:
void vpkButton_clicked();
and after
Ui::MainWindow *ui;
i added
QLineEdit *vpkPathTxt;
in mainwindow.cpp:
after
ui->setupUi(this);
i added
connect( this->ui->vpkButton, SIGNAL( clicked() ), this, SLOT(vpkButton_clicked()) );
to connect my ui button to the proper slot, the issue was getting the string from vpkButton_clicked() to display in the line edit i made in the designer,
what ended up working for me was adding this next:
vpkPathTxt = this->ui->vpkPathTxt;
the function in my main.cpp became very easy:
(QString declarations at top outside voids)
void MainWindow::vpkButton_clicked()
{
vpkName = QFileDialog::getOpenFileName(this,
tr("Open VPK File"), "~/", tr("VPK Files (*_dir.vpk)"));
vpkPathTxt->setText(vpkName);
qDebug() << vpkName;
}
the reason i am ask is because it seems a little too easy to be reliable, and the fact that i havent seen it done like this,
any input welcome
thankyou
One problem with your slot is that you don't consider the case where the user discards the "open file" dialog. In this case, the function QFileDialog::getOpenFileName returns a null QString, so you should only proceed with your logic if the return value was not a null string:
if (!vpkName.isNull()) {
...
}
The second problem is as follows and I made some assumptions since I don't see your full code:
I guess you want to load a file using the file name the user has chosen in the dialog. But you set the file name in the line edit too, which the user can edit by hand. I also guess that the actual file loading happens in a different step (i.e. after clicking another button), so after the user has edited the file name by hand in the line edit it won't be the same than in your local variable vpkName.
When loading the file I'd read the contents of the line edit instead of the variable vpkName so the edit made by hand will be respected.
A different method is to also watch for editing of the line edit and reflect the changes in your variable too. Then it will be ok to read the variable instead of the line edit when loading the file later on.