用到StatusBar是因为,需要显示一下TCP的网络信息,IP或者端口以及当前的状态之类的。
很简单,首先QMainWindow中有一个函数叫
void QMainWindow::setStatusBar(QStatusBar *statusbar)
//Sets the status bar for the main window to statusbar.
//Setting the status bar to 0 will remove it from the main window. Note that QMainWindow //takes ownership of the statusbar pointer and deletes it at the appropriate time.
因此在我们使用之前先创建一个QStatusBar的对象,然后添加就好了。
QStatusBar提供了三种类别的信息显示,临时信息、普通信息、永久信息。
临时信息
void showMessage(const QString &text, int timeout = 0);
这个函数的作用效果就是可以显示text内容,后面的timeout是持续时间。这个会占用普通信息显示的位置,因为只存在一段时间,因此叫临时的。
普通信息
普通信息,可以通过
void addWidget(QWidget *widget, int stretch = 0);
l_tcp_state = new QLabel("listening");
l_tcp_parm = new QLabel("127.0.0.1:8899");
bar->addWidget(l_tcp_parm);
bar->addWidget(l_tcp_state);
addWdiget函数来添加相应的空间,我这里添加了Qlable控件,来标准Ip和port,显示效果如下:
永久信息
void addPermanentWidget(QWidget *widget, int stretch = 0);
通过这个函数添加相应控件,这里的显示会显示到statusBar的右侧,并且不会被临时信息覆盖。
样式修改
void setSizeGripEnabled(bool);
这句代码可以控制右下角的小三角是否显示。
可以看到普通信息那里存在一个竖杠,我么也可以通过,修改stylesheet来消除它。
satausBar->setStyleSheet(QString("QStatusBar::item{border: 0px}"));
CPP完整代码
l_tcp_state = new QLabel("listening");
l_tcp_parm = new QLabel("127.0.0.1:8899");
sarWidget = new SarWidget();
bar = new QStatusBar();
bar->addWidget(l_tcp_parm);
bar->addPermanentWidget(l_tcp_state);
bar->setSizeGripEnabled(true);
bar->setStyleSheet(QString("QStatusBar::item{border: 0px}"));
this->setStatusBar(bar);