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

橙三吉。 提交于 2019-12-06 16:59:08

问题


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?


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/20794768/qt-add-a-file-selection-field-on-the-form-qlineedit-and-browse-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!