Qt: add a file selection field on the form (QLineEdit and "browse" button)
Asked Answered
S

2

28

I need to display QLineEdit with "Browse" button at my form. When user clicks button, QFileDialog should be opened, and so on.

This is pretty common thing, but I can't find ready-made solution for that. I expected in Qt Designer some widget like QFileSelect, or something like that, but found nothing similar.

Should I implement it by hand? Or, what is the correct way to do this?

Splayfoot answered 27/12, 2013 at 4:32 Comment(0)
J
22

Should I implement it by hand? Or, what is the correct way to do this?

Yes, I agree with you that it is a common thing, but unfortunately you will need to implement this yourself. The good news is that you can do this easily by something like this:

MyMainWindow::createUI()
{
    label = new QLabel("foo");
    button = new QPushButton("Browse");
    connect(button, SIGNAL(clicked()), SLOT(browse()));
    layout = new QHorizontalLayout();
    layout->addWidget(label);
    layout->addWidget(button);
    setLayout(layout);
}

void MyMainWindow::browse()
{
    QString directory = QFileDialog::getExistingDirectory(this,
                            tr("Find Files"), QDir::currentPath());

    if (!directory.isEmpty()) {
        if (directoryComboBox->findText(directory) == -1)
            directoryComboBox->addItem(directory);
        directoryComboBox->setCurrentIndex(directoryComboBox->findText(directory));
    }
}
Janelljanella answered 27/12, 2013 at 6:59 Comment(3)
Thanks, I just wanted to make sure I'm not going to re-invent the wheel.Splayfoot
This is not using QLineEdit though as asked by OP, so the text (path to the folder) is not viewable and editable, or is it?White
Does anyone have an idea why this isn't included in qt by default? It seems like one of the most widely used gui elements.Dorothy
W
0

Using Qt Creator, in your Form Layout, you can also add an Horizontal Layout instead of a Line Edit in the form and in that Horizontal Layout add a Line Edit and a Tool Button after that Line Edit. Then connect this Tool Button to a QFileDialog like explain on Laszlo answer. So this will keep your Form Layout structure.

Weitman answered 19/7 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.