formulaLabel->setIndent(3); // 缩进
statusBar()->addWidget(locationLabel); // 伸缩因子0,意味着不喜欢被拉伸。
statusBar()->addWidget(formulaLabel, 1); // 伸缩因子1,窗体size 改变时被扩展
源代码下载地址:
http://cid-620792b9d0909341.skydrive.live.com/self.aspx/.Public/src/StatusBar状态栏.rar
//
// main.cpp
#include <QApplication>
#include <QTableWidgetItem>
#include <QTableWidget>
#include <QSettings>
#include <QtGui>
#include <QLabel>
#include "MainWindow.h"
#pragma comment(lib, "QtCore4.lib")
#pragma comment(lib, "QtGui4.lib")
class Cell : public QTableWidgetItem
{
};
class Spreadsheet : public QTableWidget
{
public:
Spreadsheet(QWidget *parent = 0);
void clear();
QString currentLocation() const;
private:
enum { RowCount = 999, ColumnCount = 26 };
};
Spreadsheet::Spreadsheet(QWidget *parent)
: QTableWidget(parent)
{
setItemPrototype(new Cell);
clear();
}
void Spreadsheet::clear()
{
setRowCount(0);
setColumnCount(0);
setRowCount(RowCount);
setColumnCount(ColumnCount);
for (int i = 0; i < ColumnCount; ++i) {
QTableWidgetItem *item = new QTableWidgetItem;
item->setText(QString(QChar('A' + i)));
setHorizontalHeaderItem(i, item);
}
// 设置当前单地元格为(0, 0)
setCurrentCell(0, 0);
}
MainWindow::MainWindow()
{
spreadsheet = new Spreadsheet;
QSettings settings("Software Inc.", "Spreadsheet");
QRect rect = settings.value("geometry",
QRect(200, 200, 400, 400)).toRect();
move(rect.topLeft());
resize(rect.size());
setCentralWidget(spreadsheet);
// 只需要在QMainWindow 的构造函数中调用statusBar() 就会在窗体底部出现状态栏
locationLabel = new QLabel(" W999 ");
locationLabel->setAlignment(Qt::AlignHCenter); // 设置QLabel 的Text 居中对齐
locationLabel->setMinimumSize(locationLabel->sizeHint()); // 设置QLabel 的最小尺寸
connect(spreadsheet, SIGNAL(currentCellChanged(int, int, int, int)),
this, SLOT(updateStatusBar()));
statusBar()->addWidget(locationLabel);
updateStatusBar();
}
void MainWindow::updateStatusBar()
{
locationLabel->setText(spreadsheet->currentLocation());
}
// 将数字0~25 表示的列,映射成字母A ~ Z 表示的列
QString Spreadsheet::currentLocation() const
{
return QChar('A' + currentColumn())
+ QString::number(currentRow() + 1);
}
void MainWindow::closeEvent(QCloseEvent *event)
{
QSettings settings("Software Inc.", "Spreadsheet");
settings.setValue("geometry", geometry());
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
//