【Qt官方例程学习笔记】Getting Started Programming with Qt Widgets

时间:2024-01-08 15:57:38

创建一个QApplication对象,用于管理应用程序资源,它对于任何使用了Qt Widgets的程序都必要的。对于没有使用Qt Widgets 的GUI应用,可以使用QGuiApplication代替。

QApplication::exec() 进入事件循环。Qt应用运行时,会产生事件并被发送到应用的widgets。事件举例:鼠标点击和键盘输入。

更多相关阅读:

https://doc.qt.io/qt-5/application-windows.html

https://doc.qt.io/qt-5/eventsandfilters.html

打开文件发生错误时,发出警告信息:

      if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, "Warning", "Cannot open file: " + file.errorString());
return;
}

获取文件全部字符:

      setWindowTitle(fileName);
QTextStream in(&file);
QString text = in.readAll();

保存全部字符到文件

      QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QFile::Text)) {
QMessageBox::warning(this, "Warning", "Cannot save file: " + file.errorString());
return;
}
setWindowTitle(fileName);
QTextStream out(&file);
QString text = ui->textEdit->toPlainText();
out << text;
file.close();

打印支持:

qtHaveModule(printsupport): QT += printsupport
requires(qtConfig(fontdialog))
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printer)
#if QT_CONFIG(printdialog)
#include <QPrintDialog>
#endif // QT_CONFIG(printdialog)
#include <QPrinter>
#endif // QT_CONFIG(printer)
#endif // QT_PRINTSUPPORT_LIB ... void Notepad::print()
{
#if QT_CONFIG(printer)
QPrinter printDev;
#if QT_CONFIG(printdialog)
QPrintDialog dialog(&printDev, this);
if (dialog.exec() == QDialog::Rejected)
return;
#endif // QT_CONFIG(printdialog)
ui->textEdit->print(&printDev);
#endif // QT_CONFIG(printer)
}

复制、剪切、粘贴

void Notepad::copy()
{
#if QT_CONFIG(clipboard)
ui->textEdit->copy();
#endif
} void Notepad::cut()
{
#if QT_CONFIG(clipboard)
ui->textEdit->cut();
#endif
} void Notepad::paste()
{
#if QT_CONFIG(clipboard)
ui->textEdit->paste();
#endif
}

撤销和重做

void Notepad::undo()
{
ui->textEdit->undo();
} void Notepad::redo()
{
ui->textEdit->redo();
}

设置字体和斜体/加粗等,设置斜体/加粗时,可以只对选中文字生效:

void Notepad::selectFont()
{
bool fontSelected;
QFont font = QFontDialog::getFont(&fontSelected, this);
if (fontSelected)
ui->textEdit->setFont(font);
} void Notepad::setFontUnderline(bool underline)
{
ui->textEdit->setFontUnderline(underline);
} void Notepad::setFontItalic(bool italic)
{
ui->textEdit->setFontItalic(italic);
} void Notepad::setFontBold(bool bold)
{
bold ? ui->textEdit->setFontWeight(QFont::Bold) :
ui->textEdit->setFontWeight(QFont::Normal);
}

关于对话框:

void Notepad::about()
{
QMessageBox::about(this, tr("About MDI"),
tr("The <b>Notepad</b> example demonstrates how to code a basic "
"text editor using QtWidgets")); }