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

14,332

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));
    }
}
Share:
14,332
Dmitry Frank
Author by

Dmitry Frank

I'm a passionate software engineer with strong background in low-level parts (MCU real-time kernels, C, Assembler), and experienced in higher-level technologies as well: Go, C++, JavaScript, and many others. Author of the well-formed and carefully tested real-time kernel for 16- and 32-bit MCUs: TNeo, which is now used by several companies. One of my hobby projects is a geeky bookmarking service written in Go and PostgreSQL: Geekmarks. Some of my articles: How I ended up writing a new real-time kernel How do JavaScript closures work under the hood Unit-testing (embedded) C applications with Ceedling Object-oriented techniques in C See more at dmitryfrank.com

Updated on June 11, 2022

Comments

  • Dmitry Frank
    Dmitry Frank about 2 years

    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?