补充:
QGridLayout中的 addwidget参数的意义
依次代表 行 列 占用行数 占用列数
主要头文件:
QNetworkInterface
QHostInfo
主要函数
QString LocalHostName=QHostInfo::localHostName();
//获得本机主机名
QHostInfo hostInfo=QHostInfo::fromName(LocalHostName);//根据主机名的信息,获得ip地址信息
QList<QHostAddress> ListAdress=hostInfo.addresses();//获得主机的ip地址列表
具体代码如下
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QPushButton>
#include<QLineEdit>
#include<QLabel>
#include<QGridLayout>
#include<QMessageBox>
#include<QtNetwork/QNetworkInterface>
#include<QtNetwork/QHostInfo>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
void getHostInformation();
~Widget();
private:
QPushButton *detalBtn;
QLineEdit * LineEditLocalHostName;
QLineEdit *LineEditAdress;
QLabel *hostLabel;
QLabel *ipLabel;
QGridLayout *mainLayout;
public slots:
void slotDetal();
};
#endif // WIDGET_H
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
hostLabel= new QLabel(this);
hostLabel->setText(QStringLiteral("主机名"));
ipLabel=new QLabel(this);
ipLabel->setText(QStringLiteral("ip地址"));
LineEditAdress=new QLineEdit(this);
LineEditLocalHostName= new QLineEdit(this);
detalBtn=new QPushButton(this);
mainLayout=new QGridLayout(this);
mainLayout->addWidget(hostLabel,0,1);
mainLayout->addWidget(LineEditLocalHostName,0,2);
mainLayout->addWidget(ipLabel,1,1);
mainLayout->addWidget(LineEditAdress,1,2);
mainLayout->addWidget(detalBtn,2,1,1,2);//行 列 占用行数 占用列数
detalBtn->setText(QStringLiteral("详细"));
getHostInformation();
connect(detalBtn,&QPushButton::clicked,this,&Widget::slotDetal);
}
void Widget::getHostInformation()
{
QString LocalHostName=QHostInfo::localHostName();
//获得本机主机名
LineEditLocalHostName->setText(LocalHostName);
QHostInfo hostInfo=QHostInfo::fromName(LocalHostName);//根据主机名的信息,获得ip地址信息
QList<QHostAddress> ListAdress=hostInfo.addresses();//获得主机的ip地址列表
LineEditAdress->setText(ListAdress.at(1).toString());
}
Widget::~Widget()
{
}
void Widget::slotDetal()
{
QString detail="";
QList<QNetworkInterface> list=QNetworkInterface::allInterfaces();//提供主机ip地址和网络接口
for(int i=1;i<list.count();i++)
{
QNetworkInterface interface=list.at(i);
detail=detail+tr("设备")+interface.name()+"\n";
detail=detail+tr("硬件地址")+interface.hardwareAddress()+"\n";
QList<QNetworkAddressEntry> entryList=interface.addressEntries();//提供子网掩码和ip地址以及广播地址
for(int j=1;j<entryList.count();j++)
{
QNetworkAddressEntry entry=entryList.at(j);
detail+=" "+tr("ip")+entry.ip().toString()+"\n";
detail+=" "+tr("子网掩码")+entry.netmask().toString()+"\n";
detail+=" "+tr("广播地址")+entry.broadcast().toString()+"\n";
}
}
QMessageBox::information(this,tr("detail"),detail);
}