Qt学习例子8——filechooser

这篇博客介绍了如何在Qt中使用文件对话框加载文件,通过分析`filechooser.h`,`filechooser.cpp`和`main.cpp`的代码示例,展示了信号与槽的机制以及布局管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件对话框,加载文件的

 

//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鈥斺攆ilechooser

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值