一、标准对话框
Qt提供了一些常用的标准对话框,如打开文件对话框、选择颜色对话框、信息提示和确认选择对话框、标准输入对话框等。
1、预定义标准对话框
(1)QFileDialog 文件对话框
- QString getOpenFileName() 打开一个文件
- QstringList getOpenFileNames() 打开多个文件
- QString getSaveFileName() 选择保存一个文件
- QString getExistingDirectory() 选择一个已有目录
- QUrl getOpenFileUrl() 打开一个网络文件
(2)QColorDialog 颜色对话框
- QColor getColor() 选择颜色
(3)QFontDialog 选择字体
- QFont getFont() 选择字体
(4)QInputDialog 输入对话框
- QString getText() 的呼入单行文字
- int getInt() 输入整数
- double getDouble() 输入浮点数
- QString getItem() 从一个下拉列表中选择输入
- QString getMultiLineText() 输入多行字符串
(5)QMessageBox 消息对话框
- StandardButton information() 信息提示对话框
- StandardButton question() 询问并获取是否确定对话框
- StandardButton warning() 警告信息提示对话框
- StandardButton critical() 错误信息提示对话框
- void about() 设置自定义信息的关于对话框
- void aboutQt() 关于Qt的对话框
2、实现工具
(1)创建项目,基于QDialog
(2)添加组件
(3)实现信号与槽
#include "dialog.h"
#include "ui_dialog.h"
#include <QFileDialog>
#include <QColorDialog>
#include <QFontDialog>
#include <QInputDialog>
#include <QMessageBox>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_btnClearText_clicked()
{
ui->plainTextEdit->clear();
}
void Dialog::on_btnOpenFile_clicked()
{
QString strCurPath = QDir::currentPath();
QString strTitle = "选择文件对话框";
QString strFilter = "文本文件(*.txt);;图片文件(*.ipg *.png);;所有格式(*.*)"; // 文件选择过滤器
QString strFileName = QFileDialog::getOpenFileName(this, strTitle, strCurPath,
strFilter);
if(strFileName.isEmpty())
{
return;
}
ui->plainTextEdit->appendPlainText(strFileName);
}
void Dialog::on_btnOpenFiles_clicked()
{
QString strCurPath = QDir::currentPath();
QString strTitle = "选择文件对话框";
QString strFilter = "文本文件(*.txt);;图片文件(*.ipg *.png);;所有格式(*.*)"; // 文件选择过滤器
QStringList FileNames = QFileDialog::getOpenFileNames(this, strTitle, strCurPath,
strFilter);
if(FileNames.count() == 0)
{
return;
}
foreach (QString strFileName, FileNames)
{
ui->plainTextEdit->appendPlainText(strFileName);
}
}
void Dialog::on_btnSelectDir_clicked()
{
QString strCurPath = QDir::currentPath();
QString strTitle = "选择文件对话框";
QString strSelectDir = QFileDialog::getExistingDirectory(this, strTitle, strCurPath,
QFileDialog::ShowDirsOnly);
if(strSelectDir.isEmpty())
{
return;
}
ui->plainTextEdit->appendPlainText(strSelectDir);
}
void Dialog::on_btnSaveFile_clicked()
{
QString strCurPath = QCoreApplication::applicationDirPath();
QString strTitle = "选择文件对话框";
QString strFilter = "文本文件(*.txt);;图片文件(*.ipg *.png);;所有格式(*.*)"; // 文件选择过滤器
QString strFileName = QFileDialog::getSaveFileName(this, strTitle, strCurPath,
strFilter);
if(strFileName.isEmpty())
{
return;
}
ui->plainTextEdit->appendPlainText(strFileName);
}
void Dialog::on_btnSelectColor_clicked()
{
QPalette pal = ui->plainTextEdit->palette();
QColor initColor = pal.color(QPalette::Text);
QColor color = QColorDialog::getColor(initColor, this, "选择颜色");
if(!color.isValid())
{
return;
}
pal.setColor(QPalette::Text, color);
ui->plainTextEdit->setPalette(pal);
}
void Dialog::on_btnSelectFont_clicked()
{
bool ok = false;
QFont initFont = ui->plainTextEdit->font();
QFont font = QFontDialog::getFont(&ok, initFont, this, "选择字体");
if(!ok)
{
return;
}
ui->plainTextEdit->setFont(font);
}
void Dialog::on_btnInputString_clicked()
{
QString strTitle = "输入文字对话框";
QString strLabel = "请输入文字";
QString strDefault = "默认文字";
QLineEdit::EchoMode echoMode = QLineEdit::Normal;
bool ok = false;
QString str = QInputDialog::getText(this, strTitle, strLabel,
echoMode, strDefault, &ok);
if(!ok)
{
return;
}
ui->plainTextEdit->appendPlainText(str);
}
void Dialog::on_btnInputInt_clicked()
{
QString strTitle = "输入整数对话框";
QString strLabel = "请输入数字";
int nDefault = ui->plainTextEdit->font().pointSize();
int nMinValue = 0, nMaxValue = 100;
bool ok = false;
int nValue = QInputDialog::getInt(this, strTitle, strLabel, nDefault,
nMinValue, nMaxValue, 1, &ok);
if(!ok)
{
return;
}
QFont font = ui->plainTextEdit->font();
font.setPointSize(nValue);
ui->plainTextEdit->setFont(font);
ui->plainTextEdit->appendPlainText(QString::asprintf("输入整数:%d", nValue));
}
void Dialog::on_btnInputFloat_clicked()
{
QString strTitle = "输入整数对话框";
QString strLabel = "请输入数字";
double dDefault = 10.123;
double dMinValue = 0.0, dMaxValue = 100.0;
bool ok = false;
double dValue = QInputDialog::getDouble(this, strTitle, strLabel, dDefault,
dMinValue, dMaxValue, 3, &ok);
if(!ok)
{
return;
}
ui->plainTextEdit->appendPlainText(QString::asprintf("输入整数:%.3lf", dValue));
}
void Dialog::on_btnInputSelect_clicked()
{
QStringList items;
items << "条目1" << "条目2" << "条目3" << "条目4";
QString strTitle = "输入条目对话框";
QString strLabel = "请选择一个条目";
bool ok = false;
QString str = QInputDialog::getItem(this, strTitle, strLabel, items, 0,
true, &ok);
if(!ok || str.isEmpty())
{
return;
}
ui->plainTextEdit->appendPlainText(str);
}
void Dialog::on_btnQuestion_clicked()
{
QString strTitle = "Question消息框";
QString strLabel = "选择是与否";
QMessageBox::StandardButton result = QMessageBox::question(this, strTitle, strLabel,
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
QMessageBox::Cancel);
if(result == QMessageBox::Yes)
{
ui->plainTextEdit->appendPlainText("Yes");
}
else if (result == QMessageBox::No)
{
ui->plainTextEdit->appendPlainText("No");
}
else if (result == QMessageBox::Cancel)
{
ui->plainTextEdit->appendPlainText("Cancel");
}
}
void Dialog::on_btnInformation_clicked()
{
QMessageBox::information(this, "Information对话框", "信息", QMessageBox::Ok);
}
void Dialog::on_btnWarning_clicked()
{
QMessageBox::warning(this, "Warning对话框", "警告", QMessageBox::Ok);
}
void Dialog::on_btnCritical_clicked()
{
QMessageBox::critical(this, "Critical对话框", "错误", QMessageBox::Ok);
}
void Dialog::on_btnAbout_clicked()
{
QMessageBox::about(this, "About对话框", "关于");
}
void Dialog::on_btnAboutQt_clicked()
{
QMessageBox::aboutQt(this, "About对话框");
}
二、自定义标准对话框
1、实现工具
- QWDialogSize 设置表格行列数对话框
- QWDialogHeaders 设置表头对话框
- QWDialogLocate 单元格定位于文字设置对话框
(1)创建项目,基于QMainWindow
(2)添加组件
#include "qdialogsetsize.h"
#include "ui_qdialogsetsize.h"
#include <QMessageBox>
int QDialogSetSize::rowCount()
{
return ui->spinBoxRow->value();
}
int QDialogSetSize::columnCount()
{
return ui->spinBoxColumn->value();
}
void QDialogSetSize::setRowColumns(int nRow, int nColumn)
{
ui->spinBoxRow->setValue(nRow);
ui->spinBoxColumn->setValue(nColumn);
}
QDialogSetSize::QDialogSetSize(QWidget *parent) :
QDialog(parent),
ui(new Ui::QDialogSetSize)
{
ui->setupUi(this);
}
QDialogSetSize::~QDialogSetSize()
{
QMessageBox::information(this, "", "设置大小对话框已经退出");
delete ui;
}
(3)添加设置表格行列数UI于类
(4)添加设置表头的UI与类
#include "qdialogsetheaders.h"
#include "ui_qdialogsetheaders.h"
QDialogSetHeaders::QDialogSetHeaders(QWidget *parent) :
QDialog(parent),
ui(new Ui::QDialogSetHeaders)
{
ui->setupUi(this);
theModel = new QStringListModel(this);
ui->listView->setModel(theModel);
}
QDialogSetHeaders::~QDialogSetHeaders()
{
QMessageBox::information(this, "", "设置表头对话框退出");
delete ui;
}
void QDialogSetHeaders::setStringList(QStringList strList)
{
theModel->setStringList(strList);
}
QStringList QDialogSetHeaders::getStringList()
{
return theModel->stringList();
}
(5)添加定位单元格UI与类
#include "qdialoglocate.h"
#include "ui_qdialoglocate.h"
#include <QMessageBox>
QDialogLocate::QDialogLocate(QWidget *parent) :
QDialog(parent),
ui(new Ui::QDialogLocate)
{
ui->setupUi(this);
}
QDialogLocate::~QDialogLocate()
{
QMessageBox::information(this, "", "单元格定位对话框退出");
delete ui;
}
void QDialogLocate::setRange(int nRow, int nColumn)
{
ui->spinBoxRow->setRange(0, nRow - 1);
ui->spinBoxCol->setRange(0, nColumn - 1);
}
void QDialogLocate::setValue(int nRow, int nColumn)
{
ui->spinBoxRow->setValue(nRow);
ui->spinBoxCol->setValue(nColumn);
}
#include <mainwindow.h>
void QDialogLocate::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event)
MainWindow *parent = (MainWindow*)parentWidget();
parent->setActLocateEnable(true);
parent->resetDlgLocate();
}
void QDialogLocate::on_btnSetText_clicked()
{
int row = ui->spinBoxRow->value();
int col = ui->spinBoxCol->value();
MainWindow *parent = (MainWindow*)parentWidget();
parent->setCelltext(row, col, ui->lineEdit->text());
if(ui->checkBoxAddRow->isChecked())
{
ui->spinBoxRow->setValue(ui->spinBoxRow->value() + 1);
}
if(ui->checkBoxAddCol->isChecked())
{
ui->spinBoxCol->setValue(ui->spinBoxCol->value() + 1);
}
}
(6)设置主程序功能
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
theModel = new QStandardItemModel(this);
theSelect = new QItemSelectionModel(theModel);
ui->tableView->setModel(theModel);
ui->tableView->setSelectionModel(theSelect);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setActLocateEnable(bool enable)
{
ui->actLocate->setEnabled(enable);
}
void MainWindow::resetDlgLocate()
{
dialogLocate = nullptr;
}
void MainWindow::setCelltext(int row, int col, QString strText)
{
QModelIndex index = theModel->index(row, col);
theModel->setData(index, strText, Qt::DisplayRole);
theSelect->clearSelection();
theSelect->setCurrentIndex(index, QItemSelectionModel::Select);
}
#include "qdialogsetsize.h"
void MainWindow::on_actSetSize_triggered()
{
QDialogSetSize *dlg = new QDialogSetSize(this);
dlg->setRowColumns(theModel->rowCount(), theModel->columnCount());
int ret = dlg->exec();
if(ret == QDialog::Accepted)
{
int row = dlg->rowCount();
int col = dlg->columnCount();
theModel->setRowCount(row);
theModel->setColumnCount(col);
}
delete dlg;
}
void MainWindow::on_actSetHeader_triggered()
{
if(nullptr == dialogHeader)
{
dialogHeader = new QDialogSetHeaders(this);
}
if(dialogHeader->getStringList().count() != theModel->columnCount())
{
QStringList strList;
for (int i = 0; i < theModel->columnCount(); ++i)
{
strList << theModel->headerData(i, Qt::Horizontal).toString();
}
dialogHeader->setStringList(strList);
}
int ret = dialogHeader->exec();
if(ret == QDialog::Accepted)
{
QStringList strList = dialogHeader->getStringList();
theModel->setHorizontalHeaderLabels(strList);
}
}
void MainWindow::on_actLocate_triggered()
{
ui->actLocate->setEnabled(false);
if(nullptr == dialogLocate)
{
dialogLocate = new QDialogLocate(this);
}
dialogLocate->setAttribute(Qt::WA_DeleteOnClose); //关闭自动删除
Qt::WindowFlags flags = dialogLocate->windowFlags();
dialogLocate->setWindowFlags(flags | Qt::WindowCloseButtonHint); //置于主界面上层
dialogLocate->setRange(theModel->rowCount(), theModel->columnCount());
QModelIndex curIndex = theSelect->currentIndex();
if(curIndex.isValid())
{
dialogLocate->setValue(curIndex.row(), curIndex.column());
}
dialogLocate->show();
}
void MainWindow::on_tableView_clicked(const QModelIndex &index)
{
if(dialogLocate != nullptr)
{
dialogLocate->setValue(index.row(), index.column());
}
}
三、多窗体应用程序设计
1、视图类
- QWidget:在没有指定父容器时,可以作为独立的窗口,指定父容器后可以作为容器的内部组件
- QDialog:设计对话框,以独立窗口显示
- QMainWindow:用于设计带有菜单栏、工具栏、状态栏的主窗口,一般独立窗口显示。
- QSplashScreen:用作应用程序启动时的splash窗口,没有边框。
- QMdiSubWindow:用于为QMdiArea提供一个子窗体,用于MDI(多文档)的设计。
- QDesktopWidget:具有多个显卡和多个显示器的系统具有多个左面,这个类提供用户桌面信息,如屏幕个数,每个屏幕的大小等。
QWindow:通过底层的窗口系统表示一个窗口类,一般作为一个父容器的嵌入式窗体,不作为独立窗体。
QObject
QWidget
QDialog
QMainWindow
QSplashScreen
QMdiSubWindow
QDesktopWidget
QWindow
2、窗体特性
(1)设置运行特性和显示特性
void QWidget::setWindowState(Qt::WindowStates windowstate)
Qt::NonModal 无模态,不会阻止其他窗体的输入
Qt::WindowModal 窗口对于其父窗口、所有的商机父窗口都是模态的
Qt::ApplicationModal 窗口对整个应用程序时模态的,阻止所有窗口的输入
void QWidget::setWindowOpacity(qreal level)
参数level是1.0(完全不透明)至0.0(完全透明)之间的数。窗口透明度缺省值为1.0,即完全不透明。
void QWidgwt::setAttribute(Qt::WidgwtAttribute attribute, bool on = true)
Qt::WA_AcceptDrops 允许窗体接受拖拽来的组件
Qt::WA_DeleteOnClose 窗体关闭时删除自己,释放内存
Qt::WA_Hover 鼠标进入或移除窗体时产生paint事件
Qt::WA_AcceptTouchEvents 窗体是否接受触屏事件
表示窗体类型
void QWidget::setWindowFlags(Qt::WindowFlags type)
Qt::Widget 这是QWidget类的缺省类型,如果有父窗体,就作为父窗体的子窗体,否则就作为一个独立的窗口
Qt::Window 表明这个窗体是一个窗口,通常具有窗口的边框、标题栏,而不管它是都有父窗体
Qt::Dialog 表明窗体是一个窗口,并且要显示为对话框(如:没有标题栏、没笑最小化、最大化),这是QDialog类的缺省类型
Qt::Popup 表明扯个窗体是用作弹出式菜单的窗体
Qt::Tool 表明这个窗体是工具窗体,具有更小的标题栏和关闭按钮,通常作为工具栏的窗体
Qt::ToolTip 表明这是用于ToolTip消息提示的窗体
Qt::SplashScreen 表明窗体是Splash屏幕,是QSplashScreen类的缺省类型
Qt::DeskTop 表明窗体时桌面,这是QDesktopWidget类的类型
Qt::SubWindow 表明窗体是子窗体,例如QMdiSubWindow就是这种类型
控制窗体显示效果
Qt::MSWindowsFisedSizeDialogHint 在WIndows平台上,是的窗口具有更窄的边框
Qt::FramelessWindowHint 创建无边框窗口
QindowHint要行医窗体外观定制窗体外观的常量,需要先设置Qt::Customize
Qt::CustmizeWindowHint 关闭缺省的窗口标题栏
Qt::WindowTitleHint 窗口有标题栏
Qt::WindowSystemMenuHint 有窗口系统菜单
Qt::WindowMinimizeButtonHint 有最小化按钮
Qt::WindowMaximizeButtonHint 有最大化按钮
Qt::WindowMinMaxButtonHint 有最小化、最大化按钮
Qt::WindowCloseButtonHint 有关闭按钮
Qt::wContextHelpButtonHint 有上下文帮助按钮
Qt::WindowStaysOnTopHint 窗口总是处于最上层
Qt::WindowStaysOnBottomHint 窗口总是处于最下层
Qt::WindowtransparentForInput 窗口只作为输出,不接受输入
3、实现工具
(1)创建项目,基于QMainWindow
(2)添加源文件图标
(3)添加工具栏
(4)添加UI界面
(5)实现功能
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setCentralWidget(ui->tabWidget);
ui->tabWidget->setVisible(false); //不显示
}
MainWindow::~MainWindow()
{
delete ui;
}
#include <QPainter>
void MainWindow::paintEvent(QPaintEvent *event)
{
// 使用图片绘制底板
Q_UNUSED(event)
QPainter painter(this);
painter.drawPixmap(0, ui->mainToolBar->height(), width(),
height() - ui->mainToolBar->height() - ui->statusBar->height(),
QPixmap(":/images/images/back.jpg"));
}
#include "formdoc.h"
void MainWindow::on_actWidgetInsite_triggered()
{
FormDoc *formDoc = new FormDoc(this);
formDoc->setAttribute(Qt::WA_DeleteOnClose);
int cur = ui->tabWidget->addTab(formDoc, QString::asprintf("Doc %d", ui->tabWidget->count()));
ui->tabWidget->setCurrentIndex(cur);
ui->tabWidget->setVisible(true);
}
void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
if(index < 0)
{
return;
}
QWidget* tab = ui->tabWidget->widget(index);
tab->close();
}
void MainWindow::on_tabWidget_currentChanged(int index)
{
Q_UNUSED(index)
if(ui->tabWidget->count() == 0)
{
ui->tabWidget->setVisible(false);
}
}
void MainWindow::on_actWidget_triggered()
{
FormDoc *formDoc = new FormDoc();
formDoc->setAttribute(Qt::WA_DeleteOnClose);
formDoc->setWindowTitle("Widget独立窗口");
formDoc->setWindowOpacity(0.7); //半透明
formDoc->show();
}
#include "formtable.h"
void MainWindow::on_actMainWindowInsite_triggered()
{
FormTable *formtable = new FormTable(this);
formtable->setAttribute(Qt::WA_DeleteOnClose);
int cur = ui->tabWidget->addTab(formtable, QString::asprintf("Table %d", ui->tabWidget->count()));
ui->tabWidget->setCurrentIndex(cur);
ui->tabWidget->setVisible(true);
}
void MainWindow::on_actMainWindow_triggered()
{
FormTable *formtable = new FormTable(this);
formtable->setAttribute(Qt::WA_DeleteOnClose);
formtable->setWindowTitle("MainWindow独立窗口");
formtable->setWindowOpacity(0.7); //半透明
formtable->show();
}
四、MDI应用程序设计
QMdiArea(Multiple Document Interface Area)提供一个可以同时显示多个文档窗口的区域。区域本身是一个框架,每个窗口是都一个QMdiSubWindow对象。
设置MDI视图窗口模式用setViewMode()函数,有两种选择:
setViewMode()
QMdiArea::SubWindowView 传统的子窗口模式
WMdiArea::TabbedView 多页显示模式,类似tabView
1、实现工具
(1)创建项目,基于QMainWindow
(2)添加资源文件,设置界面
(3)添加UI与类
(4)实现功能
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "formdoc.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setCentralWidget(ui->mdiArea);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actDocNew_triggered()
{
FormDoc *formDoc = new FormDoc(this);
// formDoc->setAttribute(Qt::WA_DeleteOnClose); 不需要,框架会自动回收
ui->mdiArea->addSubWindow(formDoc);
formDoc->show();
ui->actCopy->setEnabled(true);
ui->actCut->setEnabled(true);
ui->actPaste->setEnabled(true);
ui->actFont->setEnabled(true);
}
#include <QMdiSubWindow>
#include <QFileDialog>
void MainWindow::on_actDocOpen_triggered()
{
bool needNew = false;
FormDoc *formDoc = nullptr;
if(ui->mdiArea->subWindowList().count() > 0)
{
formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
needNew = formDoc->isFileOpenedDoc();
}
else
{
needNew = true;
}
if(needNew)
{
formDoc = new FormDoc(this);
ui->mdiArea->addSubWindow(formDoc);
}
QString strFileName = QFileDialog::getOpenFileName(this, "打开文档", "",
"文本文件(*.txt);;所有文件(*.*)");
formDoc->loadFromFile(strFileName);
formDoc->show();
ui->actCopy->setEnabled(true);
ui->actCut->setEnabled(true);
ui->actPaste->setEnabled(true);
ui->actFont->setEnabled(true);
}
void MainWindow::on_actCloseAll_triggered()
{
ui->mdiArea->closeAllSubWindows();
ui->actCopy->setEnabled(false);
ui->actCut->setEnabled(false);
ui->actPaste->setEnabled(false);
ui->actFont->setEnabled(false);
}
void MainWindow::on_actFont_triggered()
{
FormDoc *formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
formDoc->setTextFont();
}
void MainWindow::on_actCut_triggered()
{
FormDoc *formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
formDoc->textCut();
}
void MainWindow::on_actCopy_triggered()
{
FormDoc *formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
formDoc->textCopy();
}
void MainWindow::on_actPaste_triggered()
{
FormDoc *formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
formDoc->textPaste();
}
void MainWindow::on_actMdiMode_triggered(bool checked)
{
if(checked)
{
ui->mdiArea->setViewMode(QMdiArea::TabbedView);
ui->mdiArea->setTabsClosable(true); //可关闭
ui->actCascade->setEnabled(false);
ui->actTile->setEnabled(false);
}
else
{
ui->mdiArea->setViewMode(QMdiArea::SubWindowView);
ui->actCascade->setEnabled(true);
ui->actTile->setEnabled(true);
}
}
void MainWindow::on_actCascade_triggered()
{
ui->mdiArea->cascadeSubWindows();
}
void MainWindow::on_actTile_triggered()
{
ui->mdiArea->tileSubWindows();
}
void MainWindow::on_mdiArea_subWindowActivated(QMdiSubWindow *arg1)
{
Q_UNUSED(arg1)
// 将选项变化,显示在状态栏
if(ui->mdiArea->subWindowList().count() == 0)
{
ui->actCopy->setEnabled(false);
ui->actCut->setEnabled(false);
ui->actPaste->setEnabled(false);
ui->actFont->setEnabled(false);
ui->statusBar->clearMessage();
}
else
{
FormDoc *formDoc = (FormDoc*)ui->mdiArea->activeSubWindow()->widget();
ui->statusBar->showMessage(formDoc->getCurFileName());
}
}
五、Splash与登录窗口
Qt有一个QSplashScreen类可以实现Splash窗口的功能,它提供了载入图片,自动设置窗口无边框效果功能。可以在加载界面使用。
(QMouseEvent *)event->globalPos() 获取鼠标的位置,即鼠偏离屏幕左上角的位置
pos() 获取主窗口(Widget窗口)左上角(边框的左上角,外左上角)相对于屏幕左上角的偏移位置。
1、实现工具
(1)拷贝上一个项目
(2)添加UI,选择Dialog
(3)添加登录验证
#include "mainwindow.h"
#include <QApplication>
#include "dialoglogin.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DialogLogin *dlg = new DialogLogin();
if(dlg->exec() == QDialog::Accepted)
{
MainWindow w;
w.show();
return a.exec();
}
return 0;
}
(4)鼠标和窗口位置计算方法
使用向量原理,可以得到:使用鼠标的向量减去相对向量(鼠标相对窗口的向量),可以得出目标窗口的向量。
void DialogLogin::mousePressEvent(QMouseEvent *event)
{
//左击
if(event->button() == Qt::LeftButton)
{
m_moveing = true;
m_lastPos = event->globalPos() - pos();
}
return QDialog::mousePressEvent(event);
}
void DialogLogin::mouseMoveEvent(QMouseEvent *event)
{
//移动
if(m_moveing && (event->buttons() && Qt::LeftButton))
{
move(event->globalPos() - m_lastPos);
m_lastPos = event->globalPos() - pos();
}
return QDialog::mouseMoveEvent(event);
}
void DialogLogin::mouseReleaseEvent(QMouseEvent *event)
{
//松开
Q_UNUSED(event)
m_moveing = false;
// return QDialog::mouseReleaseEvent(event);
}
(5)实现功能
#include "dialoglogin.h"
#include "ui_dialoglogin.h"
DialogLogin::DialogLogin(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogLogin)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlag(Qt::SplashScreen); //关闭边框
setFixedSize(this->width(), this->height()); // 禁止拖动窗口大小
readSettings();
}
DialogLogin::~DialogLogin()
{
delete ui;
}
void DialogLogin::mousePressEvent(QMouseEvent *event)
{
//左击
if(event->button() == Qt::LeftButton)
{
m_moveing = true;
m_lastPos = event->globalPos() - pos();
}
return QDialog::mousePressEvent(event);
}
void DialogLogin::mouseMoveEvent(QMouseEvent *event)
{
//移动
if(m_moveing && (event->buttons() && Qt::LeftButton))
{
move(event->globalPos() - m_lastPos);
m_lastPos = event->globalPos() - pos();
}
return QDialog::mouseMoveEvent(event);
}
void DialogLogin::mouseReleaseEvent(QMouseEvent *event)
{
//松开
Q_UNUSED(event)
m_moveing = false;
// return QDialog::mouseReleaseEvent(event);
}
#include <QSettings>
void DialogLogin::writeSettings()
{
// 写入注册表
QSettings settings("公司-liutt", "应用名称-text");
settings.setValue("UserName", m_user);
settings.setValue("Passwd", m_passwd);
settings.setValue("saved", ui->checkBoxSave->isChecked());
}
void DialogLogin::readSettings()
{
// 读取注册表
QSettings settings("公司-liutt", "应用名称-text");
bool saved = settings.value("saved", false).toBool(); //默认值
m_user = settings.value("UserName", "user").toString(); //默认值
QString defaultPasswd = encrypt("123456"); //加密
m_passwd = settings.value("Passwd", defaultPasswd).toString(); //默认值
if(saved)
{
ui->checkBoxSave->setChecked(true);
ui->lineEditUser->setText(m_user);
}
}
#include <QCryptographicHash>
QString DialogLogin::encrypt(const QString &str)
{
QByteArray btArray;
btArray.append(str);
QCryptographicHash hash(QCryptographicHash::Md5);
hash.addData(btArray);
QByteArray btResult = hash.result();
QString md5 = btResult.toHex();
return md5;
}
#include <QMessageBox>
void DialogLogin::on_btnOk_clicked()
{
QString strUser = ui->lineEditUser->text().trimmed();
QString strPasswd = ui->lineEditPasswd->text().trimmed();
if(strUser == m_user && encrypt(strPasswd) == m_passwd)
{
writeSettings();
accept();
}
else
{
m_tryCount++;
if(m_tryCount > 3)
{
QMessageBox::critical(this, "error", "错误次数太多,强制退出");
reject();
}
QMessageBox::warning(this, "error", "账号不存在或密码错误");
}
}