一、建立一個基於QWidget的應用,基類選擇QWidget,類名Mindowsthis
給combox添加可編輯屬性code
實現選擇目錄功能:blog
window.h中:get
#ifndef WINDOW_H #define WINDOW_H #include <QWidget> QT_BEGIN_NAMESPACE class QComboBox; QT_END_NAMESPACE class Window : public QWidget { Q_OBJECT public: Window(QWidget *parent = 0); ~Window(); private slots: void browse(); private: QComboBox *createComboBox(const QString &text = QString()); QComboBox *directoryComboBox; }; #endif // WINDOW_H
main.cpp中it
#include "window.h" #include <QtWidgets> void Window::browse() { QString directory = QDir::toNativeSeparators(QFileDialog::getExistingDirectory( this, tr("find files"), QDir::currentPath())); if (!directory.isEmpty()) { if (directoryComboBox->findText(directory) == -1) directoryComboBox->addItem(directory); directoryComboBox->setCurrentIndex(directoryComboBox->findText(directory)); } } QComboBox *Window::createComboBox(const QString &text) { QComboBox *comboBox = new QComboBox; comboBox->addItem(text); comboBox->setEditable(true); comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); return comboBox; } Window::Window(QWidget *parent) : QWidget(parent) { QPushButton *browseButton = new QPushButton(tr("&Browse..."), this); connect(browseButton, &QAbstractButton::clicked, this, &Window::browse); directoryComboBox = createComboBox(QDir::toNativeSeparators(QDir::currentPath())); QGridLayout *mainLayout = new QGridLayout(this); mainLayout->addWidget(new QLabel(tr("In directory:")), 2, 0); mainLayout->addWidget(directoryComboBox, 2, 1); mainLayout->addWidget(browseButton, 2, 2); setWindowTitle(tr("Find Files")); const QRect screenGeometry = QApplication::desktop()->screenGeometry(this); resize(screenGeometry.width() / 4, screenGeometry.height() / 6); } Window::~Window() { }