本文介绍Qt的标准对话框文件对话框,颜色对话框,字体对话框,分别定义了三个按钮点击可以弹出标准的对话框,再用网格布局对这些控件进行布局。
头文件:
#ifndef STANDARDDIALOG_H #define STANDARDDIALOG_H #include #include #include #include #include class StandardDialog : public QDialog { Q_OBJECT public: explicit StandardDialog(QWidget *parent = 0); ~StandardDialog(); private: QGridLayout *layout; QPushButton *filePushButton; QPushButton *colorPushButton; QPushButton *fontPushButton; QLineEdit *fileLineEdit; QLineEdit *fontLineEdit; QFrame *colorFrame; private slots: void slotOpenFileDlg(); void slotOpenColorDlg(); void slotOpenFontDlg(); }; #endif // STANDARDDIALOG_H |
#include "standarddialog.h" #include #include #include StandardDialog::StandardDialog(QWidget *parent) : QDialog(parent) { setWindowTitle("Standard Dialogs"); layout = new QGridLayout(this); filePushButton = new QPushButton; filePushButton->setText(tr("File Dialog")); colorPushButton = new QPushButton; colorPushButton->setText(tr("Color Dialog")); fontPushButton = new QPushButton(tr("Font Dialog"),this); fileLineEdit = new QLineEdit; colorFrame = new QFrame; colorFrame->setFrameShape(QFrame::Box); colorFrame->setAutoFillBackground(true); fontLineEdit = new QLineEdit(tr("Hello World")); /* 网格布局,addWidget常用两种重载形式: 1. void QGridLayout::addWidget ( QWidget * widget, int row, int column, Qt::Alignment alignment = 0 ) 分别是添加的控件,控件横坐标,控件竖坐标,控件对齐方式 2. void QGridLayout::addWidget ( QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan, Qt::Alignment alignment = 0 ) 分别是添加的控件,控件横坐标,控件竖坐标,控件占用布局的行数,控件占用布局的列数,对齐方式 */ 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(slotOpenFileDlg())); connect(colorPushButton,SIGNAL(clicked()),this,SLOT(slotOpenColorDlg())); connect(fontPushButton,SIGNAL(clicked()),this,SLOT(slotOpenFontDlg())); } void StandardDialog::slotOpenFileDlg() { /* 打开一个标准文件对话框,getOpenFileName是QFileDialog的静态函数,返回打开 的文件的文件名,如果点取消,返回空串,参数依次为:父窗口,窗口标题,文件 路径(如果带有文件名,则打开默认文件),筛选打开的文件类型,多个文件类型用;;分开 */ QString s = QFileDialog::getOpenFileName(this,"open file dialog","/", "C++ files(*.cpp);;c files(*.c);;Head files(*.h)"); //fileLineEdit显示打开的文件名,前加的有文件路径 fileLineEdit->setText(s.toAscii()); } void StandardDialog::slotOpenColorDlg() { /* getColor是QColorDialog的静态函数,打开标准颜色对话框,返回选中的颜色,参数 表示 对话框默认选中的颜色,isValid可以判断用户选择的颜色是否有效,用户点击取消 的话,isValid返回false */ QColor color = QColorDialog::getColor(Qt::blue); if(color.isValid()) { //如果颜色有效的话,将colorFrame设置为选中的颜色 colorFrame->setPalette(QPalette(color)); } } void StandardDialog::slotOpenFontDlg() { //getFont是QFontDialog的一个静态函数,返回用户选择的字体,用户选择OK,参数将*ok为true, //函数返回用户选择的字体,否则为false,此时函数返回默认字体 bool ok; QFont font = QFontDialog::getFont(&ok); if(ok) { //将fontLineEdit设置为选中的字体 fontLineEdit->setFont(font); } } |