.h文件
#ifndef STANDARDDIALOGS_H
#define STANDARDDIALOGS_H
#include <QDialog>
#include <QGridLayout>
#include <QPushButton>
#include <QLineEdit>
class StandardDialogs : public QDialog
{
Q_OBJECT
public:
StandardDialogs(QWidget *parent, Qt::WindowFlags f);
~StandardDialogs();
public:
QGridLayout *layout;
QPushButton *filePushButton;
QPushButton *colorPushButton;
QPushButton *fontPushButton;
QLineEdit *fileLineEdit;
QLineEdit *fontLineEdit;
QFrame *colorFrame;
private slots:
void slotOpenbFileDlg();
void slotOpenColorDlg();
void slotOpenFontDlg();
};
#endif // STANDARDDIALOGS_H
.c文件
#include <StandardDialogs.h>
#include <QFileDialog>
#include <QString>
#include <QLineEdit>
#include <QWidget>
#include <QFontDialog>
#include <QColorDialog>
//构造初始化列表,对QDialog进行初始化
StandardDialogs::StandardDialogs(QWidget *parent,Qt::WindowFlags f):QDialog (parent,f)
{
setWindowTitle(tr("Standard Dialogs"));//设置主窗体标题
layout = new QGridLayout(this); //
filePushButton = new QPushButton;
filePushButton->setText(tr("File Doalog"));
colorPushButton = new QPushButton;
colorPushButton->setText(tr("color Dialog"));
fontPushButton = new QPushButton;
fontPushButton->setText(tr("font Dialog"));
fileLineEdit = new QLineEdit;//用来显示选择的文件名
colorFrame = new QFrame;
colorFrame->setFrameShape(QFrame::Box); //边框的形状
colorFrame->setAutoFillBackground(true); //自动更新背景颜色
fontLineEdit = new QLineEdit;
fontLineEdit->setText(tr("Hello World!!!"));
//对控件进行位置调整布局
layout->addWidget(filePushButton,0,0);
layout->addWidget(fileLineEdit,0,1);
layout->addWidget(colorPushButton,1,0);
layout->addWidget(colorFrame,1,1);
layout->addWidget(fontPushButton,2,0);
layout->addWidget(fontLineEdit,2,1);
layout->setMargin(15); //表示控件与窗体的左右边距
layout->setSpacing(10); //表示各个控件之间的上下间距
//将各个按钮的信号与曹进行连接
connect(filePushButton,SIGNAL(clicked()),this,SLOT(slotOpenbFileDlg()));
connect(colorPushButton,SIGNAL(clicked()),this,SLOT(slotOpenColorDlg()));
connect(fontPushButton,SIGNAL(clicked()),this,SLOT(slotOpenFontDlg()));
}
//文件选择事件触发执行函数
void StandardDialogs::slotOpenbFileDlg()
{
QString s = QFileDialog::getOpenFileName(this,"open file dialog","/""C++file(*.cpp);;Cfiles (*.c);;Head file(*.h)");
fileLineEdit->setText(s.toLocal8Bit());//选择文件,把文件名显示在输入框内
}
//颜色选择事件触发执行函数
void StandardDialogs::slotOpenColorDlg()
{
QColor color = QColorDialog::getColor(Qt::blue);
if(color.isValid())
{
colorFrame->setPalette(QPalette(color));//选择颜色
}
}
//字体选择事件触发执行函数
void StandardDialogs::slotOpenFontDlg()
{
bool ok;
QFont font = QFontDialog::getFont(&ok);
if(ok)
{
fontLineEdit->setFont(font);//设置字体
}
}
//析构
StandardDialogs::~StandardDialogs()
{
;
}
main.c
#include "mainwindow.h"
#include <QApplication>
#include <StandardDialogs.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//创建对象的时候要按照构造函数的模式创建,否则无法创建成功
StandardDialogs B(NULL,Qt::Dialog);
B.show();
return a.exec();
}
结果:点击不同的按键会有不同的对话框弹出,按键与对话框使用信号与曹机制连接在一起