首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Qt 文字編輯器開發實戰(一):主視窗架構、檔案操作與信號槽機制完整解析

     編輯:關於C語言

整體架構設計

繼承 QMainWindow,以 QTextEdit 為中央元件,構建標準文件型應用骨架:選單列、工具列、狀態列、動作系統。

核心類別定義

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow();
protected:
    void closeEvent(QCloseEvent *event);
private slots:
    void newFile();
    void open();
    bool save();
    bool saveAs();
    void about();
    void documentWasModified();
private:
    void createActions();
    void createMenus();
    void createToolBars();
    void createStatusBar();
    void readSettings();
    void writeSettings();
    bool maybeSave();
    void loadFile(const QString &fileName);
    bool saveFile(const QString &fileName);
    void setCurrentFile(const QString &fileName);
    QString strippedName(const QString &fullFileName);
    QTextEdit *textEdit;
    QString curFile;
    // 選單、工具列、動作指標...
};

關鍵機制實作

1. 建構與信號連接

MainWindow::MainWindow() {
    textEdit = new QTextEdit;
    setCentralWidget(textEdit);
    createActions(); createMenus(); createToolBars(); createStatusBar();
    readSettings();
    connect(textEdit->document(), SIGNAL(contentsChanged()),
            this, SLOT(documentWasModified()));
    setCurrentFile("");
}

2. 關閉事件:未儲存提示

void MainWindow::closeEvent(QCloseEvent *event) {
    if (maybeSave()) { writeSettings(); event->accept(); }
    else event->ignore();
}

3. 檔案操作核心流程

  • newFile():maybeSave() → clear() → setCurrentFile("")
  • open():maybeSave() → QFileDialog::getOpenFileName() → loadFile()
  • save():有檔名 → saveFile(curFile);無檔名 → saveAs()
  • saveAs():QFileDialog::getSaveFileName() → saveFile()

4. 修改狀態追蹤

void MainWindow::documentWasModified() {
    setWindowModified(textEdit->document()->isModified()); // 標題列顯示 *
}

5. 動作建立範例

newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
newAct->setShortcut(tr("Ctrl+N"));
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

// 剪貼簿動作啟用狀態綁定選取內容
cutAct->setEnabled(false);
copyAct->setEnabled(false);
connect(textEdit, SIGNAL(copyAvailable(bool)), cutAct, SLOT(setEnabled(bool)));
connect(textEdit, SIGNAL(copyAvailable(bool)), copyAct, SLOT(setEnabled(bool)));

下一步預告

下篇將實作 loadFile()/saveFile() 實際 I/O、最近開啟檔案記錄、尋找/取代對話框、列印支援等進階功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved