Qt学习例子8——filechooser

时间:2022-04-07 06:32:14

文件对话框,加载文件的

 

//filechooser.h

 

#ifndef FILECHOOSER_H
#define FILECHOOSER_H
#include <QWidget>
#include <QResizeEvent>
class QLineEdit;
class QPushButton;
class FileChooser : public QWidget
{
    Q_OBJECT
public:
    FileChooser(QWidget *parent = 0);
    QString file()const;
    void setFile(const QString &file);
protected:
    void moveEvent(QMoveEvent *event);
    void resizeEvent(QResizeEvent* event);
public slots:
    void chooseFile();
private:
    QLineEdit *lineEdit;
    QPushButton *button;
};
#endif // FILECHOOSER_H

 

//filechooser.cpp

 

#include "filechooser.h"
#include <QFileDialog>
#include <QLayout>
#include <QLineEdit>
#include <QPushButton>
FileChooser::FileChooser(QWidget *parent)
    : QWidget(parent)
{
    lineEdit = new QLineEdit(this);
    button = new QPushButton(tr("..."), this);
   
    lineEdit->setGeometry(5, 5, 200, 20);
    button->setGeometry(210, 5, 20, 20);
    // enter your code here
    // create a layout, set it on the widget and add the two child widgets to it
    // make a signal-slot connection between the two widgets
    //
    QHBoxLayout *lay=new QHBoxLayout(this);
    //QRect rc(0,0,445,30);
    //lay->setGeometry(rc);
    //lay->setMargin( 15);
    //lay->setSpacing( 10);
    lay->addWidget(lineEdit);
    lay->addWidget(button);
//    connect(this,SIGNAL(moveEvent(QMoveEvent*)),this,SLOT(updateSize()));
    connect(button,SIGNAL(clicked()),this,SLOT(chooseFile()));
}
void FileChooser::chooseFile()
{
    // enter your code here
    // ask the user for a file name and set its path as text of lineEdit
    //qDebug("choosing!");
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                     "D://Qt//filechooser",
                                                     tr("Files (*.cpp *.h *.pro)"));
    //注意这里/不能只有一个会被解释成转义字符
    lineEdit->setText(fileName);
}
void FileChooser::moveEvent(QMoveEvent *event)
{
    qDebug("Moving!");
}
void FileChooser::resizeEvent(QResizeEvent* event)
{
    //qDebug("Reszing!");
    int h,w;
    h=event->size().height();
    w=event->size().width();
    lineEdit->setGeometry(5,5,w*0.7-5,h-5);
    button->setGeometry(w*0.7+5,5,w*0.3-5,h-5);
}
QString FileChooser::file() const
{
    return lineEdit->text();
}
void FileChooser::setFile(const QString &file)
{
    lineEdit->setText(file);
}

 

 

//main.cpp

 

#include <QtGui/QApplication>
#include "filechooser.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    FileChooser w;
    w.show();
    return a.exec();
}

 

 

程序运行结果图:

Qt学习例子8——filechooser