六、标准对话框、多应用窗体

一、标准对话框

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", "账号不存在或密码错误");


    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/337505.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

uniapp组件库Popup 弹出层 的使用方法

目录 #平台差异说明 #基本使用 #设置弹出层的方向 #设置弹出层的圆角 #控制弹窗的宽度 | 高度 #内容局部滚动 #API #Props #Event 弹出层容器&#xff0c;用于展示弹窗、信息提示等内容&#xff0c;支持上、下、左、右和中部弹出。组件只提供容器&#xff0c;内部内容…

树的一些经典 Oj题 讲解

关于树的遍历 先序遍历 我们知道 树的遍历有 前序遍历 中序遍历 后序遍历 然后我们如果用递归的方式去解决&#xff0c;对我们来说应该是轻而易举的吧&#xff01;那我们今天要讲用迭代&#xff08;非递归&#xff09;实现 树的相关遍历 首先呢 我们得知道 迭代解法 本质上也…

【征服Redis12】redis的主从复制问题

从现在开始&#xff0c;我们来讨论redis集群的问题&#xff0c;在前面我们介绍了RDB和AOF两种同步机制&#xff0c;那你是否考虑过这两个机制有什么用呢&#xff1f;其中的一个重要作用就是为了集群同步设计的。 Redis是一个高性能的键值存储系统&#xff0c;广泛应用于Web应用…

Python实现稳健线性回归模型(rlm算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 稳健回归可以用在任何使用最小二乘回归的情况下。在拟合最小二乘回归时&#xff0c;我们可能会发现一些…

人才测评,招聘工程技术经理胜任素质模型与任职资格

招聘工程技术经理是企业中的重要职位之一&#xff0c;为了确保招聘到胜任的人才&#xff0c;需要制定一个胜任力素质模型和任职资格。 1.专业知识技能&#xff1a;工程技术经理需要拥有深厚的专业技术知识&#xff0c;能够熟练掌握工程设计、生产制造、质量管理、安全管理等方面…

macOS 设置屏幕常亮 不休眠

Apple M1 Pro macOS Sonoma设置“永不”防止进入休眠 macOS Sonoma 设置“永不” 防止进入休眠

开源进程/任务管理服务Meproc使用之HTTP API

本文讲述如何使用开源进程/任务管理服务Meproc的HTTP API管理整个服务。 Meproc所提供的全部 API 的 URL 都是相同的。 http://ip:port/proc例如 http://127.0.0.1:8606/proc在下面的小节中&#xff0c;我们使用curl命令向您展示 API 的方法、参数和请求正文。 启动任务 …

Tensorflow 入门基础——向LLM靠近一小步

进入tensflow的系统学习&#xff0c;向LLM靠拢。 目录 1. tensflow的数据类型1.1 数值类型1.2 字符串类型1.3 布尔类型的数据 2. 数值精度3. 类型转换3.1 待优化的张量 4 创建张量4.1 从数组、列表对象创建4.2 创建全0或者1张量4.3 创建自定义数值张量 5. 创建已知分布的张量&…

Linux重定向:深入理解与实践

&#x1f3ac;慕斯主页&#xff1a;修仙—别有洞天 ♈️今日夜电波&#xff1a;晴る—ヨルシカ 0:20━━━━━━️&#x1f49f;──────── 4:30 &#x1f504; ◀️ ⏸ ▶️ ☰ &…

深度学习记录--Momentum gradient descent

Momentum gradient descent 正常的梯度下降无法使用更大的学习率&#xff0c;因为学习率过大可能导致偏离函数范围&#xff0c;这种上下波动导致学习率无法得到提高&#xff0c;速度因此减慢(下图蓝色曲线) 为了减小波动&#xff0c;同时加快速率&#xff0c;可以使用momentum…

linux内核原理--分页,页表,内核线性地址空间,伙伴系统,内核不连续页框分配,内核态小块内存分配器

1.分页&#xff0c;页表 linux启动阶段&#xff0c;最初运行于实模式&#xff0c;此阶段利用段寄存器&#xff0c;段内偏移&#xff0c;计算得到物理地址直接访问物理内存。 内核启动后期会切换到保护模式&#xff0c;此阶段会开启分页机制。一旦开启分页机制后&#xff0c;内…

Navicat平替工具,一款免费开源的通用数据库工具

前言 前段时间有小伙伴在群里提问说&#xff1a;因为公司不允许使用破解版的Navicat&#xff0c;有好用的Navicat平替工具推荐吗&#xff1f;今天分享一款免费开源的通用数据库工具&#xff1a;DBeaver。 DBeaver工具介绍 DBeaver是一款免费的跨平台数据库工具&#xff0c;适…

转转交易猫自带客服多模板全开源完整定制版源码

商品发布&#xff1b; 请在后台商品添加成功后&#xff0c; 再点击该商品管理&#xff0c;可重新编辑当前商品的所有信息及配图以及支付等等相关信息 可点击分享或者跳转&#xff0c;将链接地址进行发布分享 请在手机端打开访问 访问商品主要模板文件路径目录 咸鱼&#…

四个简单的bat脚本

Windows11 最大劝退点就是这个右键菜单&#xff0c;复制粘贴都变成一点点的小图标&#xff0c;最气人的是点击底部的显示更多选项才能展示全部功能。让许多本来点一次就能完成的操作变成两次。其实使用一个小命令就能修改回win10版本的菜单。四个简单的bat脚本&#xff0c;能完…

Java大型企业进销存系统

技术框架&#xff1a; SpringBoot Spring Data Jpa SpringMvc Shiro安全认证 完整权限系统 easyui 有需要的可以联系我。 运行环境&#xff1a; jdk8 IntelliJ IDEA maven 系统介绍&#xff1a; 导航菜单&#xff1a;系统菜单、销售管理、库存管理、统计报表、基础…

Ubuntu使用docker-compose安装redis

ubuntu环境搭建专栏&#x1f517;点击跳转 Ubuntu系统环境搭建&#xff08;十三&#xff09;——使用docker-compose安装redis 文章目录 Ubuntu系统环境搭建&#xff08;十三&#xff09;——使用docker-compose安装redis1.搭建文件夹2.docker-compose.yaml配置文件3.redis.co…

【JavaWeb】XML Tomcat10 HTTP

文章目录 一、XML1.1常见配置文件类型 二、Tomcat102.1 WEB项目的标准结构2.2 Tomcat目录2.3 WEB项目部署的方式2.4 IDEA中开发并部署运行WEB项目2.5 处理配置文件2.6 处理依赖jar包问题2.7 IDEA部署-运行web项目 三、HTTP3.1 HTTP协议的会话方式3.2 请求和响应报文3.3.1 报文的…

数字IC后端设计实现 | PR工具中到底应该如何控制density和congestion?(ICC2Innovus)

吾爱IC社区星友提问&#xff1a;请教星主和各位大佬&#xff0c;对于一个模块如果不加干预工具会让inst挤成一团&#xff0c;后面eco修时序就没有空间了。如果全都加instPadding会导致面积不够overlap&#xff0c;大家一般怎么处理这种问题&#xff1f; 在数字IC后端设计实现中…

前端实现贪吃蛇功能

大家都玩过贪吃蛇小游戏&#xff0c;控制一条蛇去吃食物&#xff0c;然后蛇在吃到食物后会变大。本篇博客将会实现贪吃蛇小游戏的功能。 1.实现效果 2.整体布局 /*** 游戏区域样式*/ const gameBoardStyle {gridTemplateColumns: repeat(${width}, 1fr),gridTemplateRows: re…

RabbitMQ与SpringAMQP

MQ&#xff0c;中文是消息队列&#xff08;MessageQueue&#xff09;&#xff0c;字面来看就是存放消息的队列。也就是事件驱动架构中的Broker。&#xff08;经纪人&#xff01;&#xff09; 1.RabbitMQ介绍 微服务间通讯有同步和异步两种方式 同步&#xff08;通信&#xff0…
最新文章