在程式主視窗Mainwindow中,有菜單欄,工具欄,中心部件和狀态欄。前面幾個已經講過了,這次講解狀态欄的使用。
程式中有哪些不明白的類或函數,請自己檢視幫助。
1.我們在mainwindow.h中做一下更改。
加入頭檔案包含: #include <QLabel>
加入私有變量和函數:
QLabel* first_statusLabel; //聲明兩個标簽對象,用于顯示狀态資訊
QLabel* second_statusLabel;
void init_statusBar(); //初始化狀态欄
加入一個槽函數聲明:void do_cursorChanged(); //擷取光标位置資訊
2.在mainwindow.cpp中加入狀态欄初始化函數的定義。
void MainWindow::init_statusBar()
{
QStatusBar* bar = ui->statusBar; //擷取狀态欄
first_statusLabel = new QLabel; //建立标簽
first_statusLabel->setMinimumSize(150,20); //設定标簽最小尺寸
first_statusLabel->setFrameShape(QFrame::WinPanel); //設定标簽形狀
first_statusLabel->setFrameShadow(QFrame::Sunken); //設定标簽陰影
second_statusLabel = new QLabel;
second_statusLabel->setMinimumSize(150,20);
second_statusLabel->setFrameShape(QFrame::WinPanel);
second_statusLabel->setFrameShadow(QFrame::Sunken);
bar->addWidget(first_statusLabel);
bar->addWidget(second_statusLabel);
first_statusLabel->setText(tr("歡迎使用文本編輯器")); //初始化内容
second_statusLabel->setText(tr("yafeilinux制作!"));
}
這裡将兩個标簽對象加入到了主視窗的狀态欄裡,并設定了他們的外觀和初值。
3.在構造函數裡調用狀态欄初始化函數。
init_statusBar();
這時運作程式,效果如下。
4.在mainwindow.cpp中加入擷取光标位置的函數的定義。
void MainWindow::do_cursorChanged()
{
int rowNum = ui->textEdit->document()->blockCount();
//擷取光标所在行的行号
const QTextCursor cursor = ui->textEdit->textCursor();
int colNum = cursor.columnNumber();
//擷取光标所在列的列号
first_statusLabel->setText(tr("%1行 %2列").arg(rowNum).arg(colNum));
//在狀态欄顯示光标位置
}
這個函數可擷取文本編輯框中光标的位置,并顯示在狀态欄中。
5.在構造函數添加光标位置改變信号的關聯。
connect(ui->textEdit,SIGNAL(cursorPositionChanged()),this,SLOT(do_cursorChanged()));
這時運作程式。效果如下。
6.在do_file_Load函數的最後添加下面語句。
second_statusLabel->setText(tr("打開檔案成功"));
7.在saveFile函數的最後添加以下語句。
second_statusLabel->setText(tr("儲存檔案成功"));
8.在on_action_Find_triggered函數的後面添加如下語句。
second_statusLabel->setText(tr("正在進行查找"));
9.在on_action_Close_triggered函數最後添加如下語句。
first_statusLabel->setText(tr("文本編輯器已關閉"));
second_statusLabel->setText(tr("yafeilinux制作!"));
最終的mainwindow.cpp檔案内容如下。
最終的mainwindow.h檔案如下。
到這裡整個文本編輯器的程式就算寫完了。我們這裡沒有寫幫助菜單的功能實作,大家可以自己添加。而且程式中也有很多漏洞和不完善的地方,如果有興趣,大家也可以自己修改。因為時間和篇幅的原因,我們這裡就不再過多的講述。