设置状态栏
前面完成了菜单和工具栏,我们开始处理电子表格应用的状态栏。正常模式下,状态栏包含两个指示信息:当前表格单元的位置和当前表格单元的公式。状态栏也用于显示一些临时状态信息。
MainWindow的构造方法调用createStatusBar()来创建状态栏:
void MainWindow::createStatusBar()
{
locationLabel = new QLabel(" W999 ");
locationLabel->setAlignment(Qt::AlignHCenter);
locationLabel->setMinimumSize(locationLabel->sizeHint());
formulaLabel = new QLabel;
formulaLabel->setIndent(3);
statusBar()->addWidget(locationLabel);
statusBar()->addWidget(formulaLabel, 1);
connect(spreadsheet, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(updateStatusBar()));
connect(spreadsheet, SIGNAL(modified()), this, SLOT(spreadsheetModified()));
updateStatusBar();
}
QMainWindow::statusBar()方法返回一个指向status bar的指针(status bar在第一次调用时创建)。状态指示器只是简单的QLabel,其文本可以在需要的时候改变。我们已经增加了缩排标记到formulaLabel,以便文档显示与左边的label之间留有空白。当QLabel增加到状态栏时,它们自动称为状态栏的孩子。
当QStatusBar排列其显示组件时,他关心每个组件实际的大小通过QWidget::sizeHint()并调整每个可调整的组件到合适的大小。一个组件的理想大小与其内容相关,当内容调整时,理想大小也会改变。为了避免经常重新确定组件的大小,我们设置容纳"W999"的大小为最小尺寸,我们也设置对齐方式为横向中心对齐。
void MainWindow::updateStatusBar()
{
locationLabel->setText(spreadsheet->currentLocation());
formulaLabel->setText(spreadsheet->currentFormula());
}
updateStatusBar() slot修改表格单元的位置并显示其公式。当表格焦点移到另一个表格单元是这个方法被调用。当然,这个slot也作为普通函数被在createStatusBar()的末尾被调用。原因是Spreadsheet启动是不发送currentCellChanged() signal.
void MainWindow::spreadsheetModified()
{
setWindowModified(true);
updateStatusBar();
}
spreadsheetModified() slot 设置windowModified属性为true,更新title bar.