QT随笔

1、获取本机IP地址

QString MainWindow::getHostIpAddress()
{
    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&  ipAddressesList.at(i).toIPv4Address())
        {
            ipAddress = ipAddressesList.at(i).toString();
            //break;
        }
    }
    if (ipAddress.isEmpty())
    {
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
    }
    //qDebug()<< "Local ip address:" << ipAddress;  //debug
    return ipAddress;
}

2、查找可用的TCP端口号

//获取所有已占用的TCP端口号
QVector<uint16_t> MainWindow::getAllTcpConnectionsPort()
{
    QVector<uint16_t> ret;
    ULONG size = 0;
    GetTcpTable(nullptr, &size, TRUE);
    std::unique_ptr<char[]> buffer(new char[size]);
    PMIB_TCPTABLE tcpTable =    reinterpret_cast<PMIB_TCPTABLE>(buffer.get());
    if (GetTcpTable(tcpTable, &size, FALSE) == NO_ERROR)
        for (size_t i = 0; i < tcpTable->dwNumEntries; i++)
            ret.push_back(ntohs((uint16_t)tcpTable->table[i].dwLocalPort));
    std::sort(std::begin(ret), std::end(ret));
    return ret;
}

//查找可用的TPC端口
QVector<uint16_t> MainWindow::findAvailableTcpPort(uint16_t begin, uint16_t end)
{
    auto vec = getAllTcpConnectionsPort();
    QVector<uint16_t> availablePortVector;

    //在端口区间检测端口是否在占用列表中,如果不在则表示当前的端口可用并返回
    for (uint16_t port = begin; port != end; ++port)
        if (!std::binary_search(std::begin(vec), std::end(vec), port))
        {
            static int i = 0;
            availablePortVector.insert(i++,port);
            //qDebug() << port;
        }
    return availablePortVector;
}

3、tr在字符串中的用法例子

void MainWindow::setLocalAddress(QString ip,uint16_t port)
{
    _localAddress = tr("tcp://%1::%2").arg(ip).arg(port);
    qDebug() << tr("Local address is:%1").arg(_localAddress);
}

 4、选择图片并显示至QLabel

void Widget::selectImage()
{
    QString fileName = QFileDialog::getOpenFileName(
        this,
        tr("select a file."),
        "D:/",
        tr("images(*.png *jpg *bmp)"));
    if (fileName.isEmpty())
    {
        QMessageBox::warning(this, "Warning!", "Image is empty...");
    }
    else
    {
        _image = QImage(fileName);
        qDebug() << tr("Image size is %1*%2").arg(_image.height()).arg(_image.width());
    }
    ui->labelImage->setPixmap(QPixmap::fromImage(_image));
}

将QLabel放至QScoll area即可使用滚动条完整查看图片。

posted @ 2020-06-23 09:02  鸡鸣昧旦  阅读(173)  评论(0编辑  收藏  举报