QT控件之对话框
对话框
文件对话框
添加头文件#include<QFileDialog>
QfileDialog类有很多方法,可以静态使用,也可以实例化使用。
常用的有以下这些:
QFileDialog::getOpenFileName();选择打开文件路径
QFileDialog::getSaveFileName();选择保存路径
QFileDialog::getExistingDirectory();选择文件夹
返回的是整个路径。
QFileDialog::selectFile();
QFileDialog::setWindowTitle();
例如:
QFileDialog::getSaveFileName();
参数为:
父句柄,一般为0。
标题:字符串
路径:可以为空,打开的对话框定为到最后一个/,把最后的字符串作为文件名。
过滤器:"Image Files(*.bmp *.jpg)"
fileName =QFileDialog::getSaveFileName(this, tr("title"),”/root/a.bmp”,"Image Files (*.bmp)");
if (!fileName.isNull())
{
QString path =fileName;
QFile f(path);
f.open(QIODevice::ReadWrite);//打开文件
f.write(bmp);
f.close();
num++;
}
void Form1::opendialog()
{
QString file name=QFileDialog::getOpenFileName(
0,
"open the file",
QDir::home().dirName(),
"file(*.bmp *.jpg)",
0,
0);
ui->label->setText(filename);
}
输入框QinputDialog
头文件
#include<QInputDialog>
主要由四种方法:getText(),getInt(),getDouble()和getItem()
voidForm1::inputdialog()
{
QString text;
bool ok;
text=QInputDialog::getText(
this,
tr("UserName"),
tr("Please input newname"),
QLineEdit::Normal,
QDir::home().dirName(),
&ok);
if(ok&&!text.isEmpty())
{
ui->label->setText(text);
}
}
颜色框
#include<QColorDialog>
void Form1::colordialog()
{
QColor color=QColorDialog::getColor(Qt::green,this);
if(color.isValid())
{
ui->label->setText(color.name());
ui->label->setPalette(QPalette(color));
ui->label->setAutoFillBackground(true);
}
}
第1句创建标准颜色选择对话框。
第2句判断颜色是否有效。
第3句设置colorLabel显示的文本是用户从标准颜色对话框中选择的颜色的名字。
第4句通过setPalette()方法设置colorLabel的调色板信息。setPalette()方法经常用于此
种场合。
第5句也很重要,setAutoFillBackground()方法用于设置窗体能够自动填充背景。
字体框
void Form1::fontdialog()
{
bool ok;
QFont font = QFontDialog::getFont(&ok,QFont("Times",12),this);
if(ok)
{
ui->label->setFont(font);
}
else
{
}
}
信息提示框
在程序开发中,经常会遇到各种各样的消息框来给用户一些提示或提醒,Qt提供了QMessageBox类来实现此项功能。在使用QMessageBox类之前,应加入其头文件声明:
#include<QMessageBox>
QT提供了Question消息框、Information消息框、Warning消息框、Critical消息框、About消息框、AboutQt(关于Qt)消息框以及Custom(自定义)消息框等。
Question消息框、Information消息框、Warning消息框和Critical消息框的用法大同小异,这些消息框一般都包含一条提示信息、一个图标以及若干个按钮,它们的作用都是给用户提供一些提醒或一些简单的询问。
消息框的返回值是一个QMessageBox::StandardButton,这是一个枚举量,它包含了QMessageBox类默认提供的按钮提示信息,如OK、Help、Yes、No、Abort、Retry、Ignore等。
例如:
参数是(this,标题,内容,按钮列表,选择默认把焦点移动哪个按钮上)
void Form1::messdialog()
{
switch(QMessageBox::question(
this,
"titile",
"detail",
QMessageBox::Ok|QMessageBox::No,
QMessageBox::Ok)
)
{
case QMessageBox::Ok:
ui->label->setText("ok");
break;
case QMessageBox::No:
ui->label->setText("no");
break;
default:
break;
}
}
不带标题栏
QmessageBox mgb;
mgb.setWIndowFlags(Qt::FrameLessTopHint);
mgb.exec();