Russian Qt Forum
Май 03, 2024, 05:15 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало Форум WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  
  Просмотр сообщений
Страниц: 1 ... 5 6 [7]
91  Qt / Вопросы новичков / Re: tcp_client : Ноябрь 30, 2015, 14:39
Что то не получается у меня  Злой
Код:
QByteArrey data;
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
m_pTcpSocket->read(data);
m_ptxtInfo->append(codec->fromUnicode(data.toStdString());
92  Qt / Вопросы новичков / Re: tcp_client : Ноябрь 30, 2015, 00:14
Спасибо большое Вы мне очень помогли. Не сможете помочь с функцией приема ?
93  Qt / Вопросы новичков / Re: tcp_client : Ноябрь 29, 2015, 21:56
Сделал как вы сказали.  Да, действительно пробелы между символами пропали, но, что то передается до нужный символов пробелы (см. рис). Ну естественно так как я поменял функцию передачи, моя функция приема не правильно обрабатывает и ничего не принимает обратно  Грустный

Код:
void TCP_client::slotSendToServer()
{
    QByteArray arrBlock;
    QDataStream out(&arrBlock, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_5);
    QTextCodec *codec = QTextCodec::codecForName( "UTF-8" );
    out<<qint16(0) << codec->fromUnicode( m_ptxtInput->text() );

    out.device()->seek(0);
    
    out<<qint16(arrBlock.size() - sizeof(qint16));

    m_pTcpSocket->write(arrBlock);
    m_ptxtInput ->setText("");


}
Код:
 out<<qint16(arrBlock.size() - sizeof(qint16));
что это выражение значит ?
94  Qt / Вопросы новичков / Re: tcp_client : Ноябрь 29, 2015, 21:08
Я извиняюсь я начинающий программист. Прошу помощи  Улыбающийся
Цитировать
Вы отправляете UNICODE строку, которая храниться в QString. Конвертируйте ее в однобайтные кодировки перед отправкой, с помощью QTextCodec.

Так чтоли ?
Код:
void TCP_client::slotSendToServer()
{
    QByteArray arrBlock;
    QDataStream out(&arrBlock, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_5);
    out<<qint16(0) << m_ptxtInput->text();

    out.device()->seek(0);
    out<<qint16(arrBlock.size() - sizeof(qint16));
    QTextCodec* data;
    m_pTcpSocket->write(data->toUnicode(arrBlock));
    m_ptxtInput ->setText("");


}
95  Qt / Вопросы новичков / tcp_client : Ноябрь 29, 2015, 15:43
добрый день! Возникла необходимость разработать программное обеспечение, которое будет собирать значения по ЛВС с arduin. Я залил готовый скетч  echo tcp servera из библиотеки UIPEthernet.   И составил программу на в Qt, которая показана ниже.

tcp_client.h
Код:
#ifndef TCP_client_H
#define TCP_client_H

#include <QDialog>
#include <QWidget>
#include <QVBoxLayout>
#include <QTcpSocket>
#include <QTime>
#include <QDataStream>
#include <QTextEdit>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>

class TCP_client : public QDialog
{
    Q_OBJECT
private:
    QTcpSocket* m_pTcpSocket;
    quint16      m_nNextBlockSize;
    QTextEdit*     m_ptxtInfo;
    QLineEdit*      m_ptxtInput;

public:
    TCP_client (QWidget* pobj = 0);

private slots:
    void slotReadyRead();
    void slotError(QAbstractSocket::SocketError);
    void slotConnnected();
    void slotSendToServer();
};



#endif // TCP_H

tcp_client.cpp
Код:
#include "tcp_client.h"

TCP_client::TCP_client(QWidget *pwgt) :
                       QDialog(pwgt), m_nNextBlockSize(0)
{
    m_pTcpSocket = new QTcpSocket(this);

    m_pTcpSocket ->connectToHost("10.28.17.164", 1000);

    connect(m_pTcpSocket, SIGNAL(connected()), SLOT(slotConnnected()));
    connect(m_pTcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));
    connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(slotError(QAbstractSocket::SocketError))
            );
    m_ptxtInfo =new QTextEdit;
    m_ptxtInput = new QLineEdit;

    m_ptxtInfo->setReadOnly(true);

    QPushButton* pcmd = new QPushButton("&send");
    connect(pcmd, SIGNAL(clicked()), SLOT(slotSendToServer()));
    connect(m_ptxtInput, SIGNAL(returnPressed()), this, SLOT(slotSendToServer()));

    //-------------отоброжение---------------..//

    QVBoxLayout* pvbxLayout = new QVBoxLayout;
    pvbxLayout->addWidget(new QLabel ("<H1>Client</H1>"));
    pvbxLayout->addWidget(m_ptxtInfo);
    pvbxLayout->addWidget(m_ptxtInput);
    pvbxLayout->addWidget(pcmd);
    setLayout(pvbxLayout);
}

//-----------------------передача сообщения ---------------------------------
void TCP_client::slotSendToServer()
{
    QByteArray arrBlock;
    QDataStream out(&arrBlock, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_5);
    out<<qint16(0) << m_ptxtInput->text();

    out.device()->seek(0);
    out<<qint16(arrBlock.size() - sizeof(qint16));

    m_pTcpSocket->write(arrBlock);
    m_ptxtInput ->setText("");


}

//--------------------считывание собщения-------------------------//
void TCP_client::slotReadyRead()
{
    QDataStream in(m_pTcpSocket);
    in.setVersion(QDataStream::Qt_5_5);
    for(;;){
        if(!m_nNextBlockSize){
            if(m_pTcpSocket->bytesAvailable()<sizeof(qint16)){
                break;
            }
            in>>m_nNextBlockSize;
        }

        if(m_pTcpSocket->bytesAvailable()<m_nNextBlockSize){
            break;
        }

        QTime time;
        QString str;
        in>>str;

        m_ptxtInfo ->append(str);
        m_nNextBlockSize = 0;
    }
}

//-----------------------------ошибки-----------------------------//
void TCP_client::slotError(QAbstractSocket::SocketError err)
{
    QString strError =
            "Error: " +(err == QAbstractSocket::HostNotFoundError ?
                            "The host is not font." :
                        err == QAbstractSocket::RemoteHostClosedError ?
                        "The remote host is closed" :
                        err == QAbstractSocket::ConnectionRefusedError ?
                        "The conection was refused" :
                        QString (m_pTcpSocket->errorString())
                        );
    m_ptxtInfo ->append( strError);

}

void TCP_client::slotConnnected()
{
    m_ptxtInfo ->append("Соеденение устанволенно!");
}

Все работает отлично, то что я отправляю получаю обратно, но в терминале arduino получаю значение с пробелами.

 Читал вот это http://meshin1.tumblr.com/post/254097090/%D1%80%D0%B0%D0%B7%D0%B1%D0%B8%D1%80%D0%B0%D0%B5%D0%BC%D1%81%D1%8F-%D1%81-%D1%81%D0%B5%D1%80%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B5%D0%B9-%D0%B2-qiodevice. Как можно по другому реализовать код? Или как можно от дополнительный передающих байтов избавиться?
С perl скриптом все работает нормально
Код:
#!/usr/bin/perl
#tcpclient.pl

use IO::Socket::INET;

# flush after every write
$| = 1;

my ($socket,$client_socket);

# creating object interface of IO::Socket::INET modules which internally creates
# socket, binds and connects to the TCP server running on the specific port.
$socket = new IO::Socket::INET (
PeerHost => '192.168.0.6',
PeerPort => '1000',
Proto => 'tcp',
) or die "ERROR in Socket Creation : $!\n";

print "TCP Connection Success.\n";

# write on the socket to server.
$data = "DATA from Client";
print $socket "$data\n";
# we can also send the data through IO::Socket::INET module,
# $socket->send($data);

# read the socket data sent by server.
$data = <$socket>;
# we can also read from socket through recv()  in IO::Socket::INET
# $socket->recv($data,1024);
print "Received from Server : $data\n";

sleep (10);
$socket->close();
96  Qt / Вопросы новичков / Re: undefined reference : Сентябрь 21, 2015, 21:11
Все решил проблему. Спасибо за помощь.
97  Qt / Вопросы новичков / Re: undefined reference : Сентябрь 20, 2015, 23:15
кроме этого ничего в голову не лезет
Код:
    QPushButton* createButton(const QString& str){
        QPushButton* button = new QPushButton(str);
        return button;
    }
98  Qt / Вопросы новичков / Re: undefined reference : Сентябрь 20, 2015, 22:27
А как это сделать? помогите новичку ?
99  Qt / Вопросы новичков / Re: undefined reference : Сентябрь 20, 2015, 21:48
Не совсем понял, можете подробнее
Код:
return ... trololo ...;
100  Qt / Вопросы новичков / *РЕШЕНО* undefined reference : Сентябрь 20, 2015, 20:51
Добрый вечер всем. Начал изучать Qt с книжкой Qt 5.3 Макс Шлее. Остановился на калькуляторе  листинг 6.6 - 6.11. Ошибка  при компиляции. Не могу создать PushButton для Widget если я правильно выражаюсь.
calculator.h
Код:
#ifndef CALCULATOR_H
#define CALCULATOR_H

#pragma once

#include <QWidget>
#include <QStack>

class QLCDNumber;
class QPushButton;

class calculator : public QWidget
{
    Q_OBJECT

private:
    QLCDNumber*     m_plcd;
    QStack<QString> m_stk;
    QString         m_strDisplay;

public:
    calculator(QWidget *parent = 0);
    ~calculator();
    QPushButton* createButton(const QString& str);
    void         calculate (                    );

/*signals:
public slots:
    void slotButtonClicked();*/
};

#endif // CALCULATOR_H

calculator.cpp
Код:
#include "calculator.h"
#include <QLCDNumber>
#include <QGridLayout>
#include <QPushButton>
#include <QDebug>

calculator::calculator(QWidget *parent)
    : QWidget(parent)
{

    m_plcd = new QLCDNumber(12);
    m_plcd->setSegmentStyle(QLCDNumber::Flat);
    m_plcd->setMinimumSize(150, 50);

    QChar aButtons [4] [4] = {{'7', '8', '9', '/'},
                              {'4', '5', '6', '*'},
                              {'1', '2', '3', '-'},
                              {'0', '.', '=', '+'}
                             };
    
    QGridLayout* ptopLayout = new QGridLayout;
    ptopLayout->addWidget(m_plcd, 0, 0, 1, 4);

    ptopLayout->addWidget(createButton("CE"), 1, 3);

    for (int i=0; i<4; ++i){
        for(int j=0; j<4; ++j){
            ptopLayout->addWidget(createButton(aButtons[i][j]), i+2, j);
        }
    }
    setLayout(ptopLayout);
}

calculator::~calculator()
{

}

main.cpp
Код:
#include "calculator.h"
#include <QApplication>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    calculator Calculator;

    Calculator.setWindowTitle("Calculator");
    Calculator.resize(230,200);

    Calculator.show();

    return a.exec();
}

при компиляции выдает ошибку undefined reference to `calculator::createButton(QString const&)'
если вместо createButton применить new QPushButton все работает.
calculator.cpp

Код:
#include "calculator.h"
#include <QLCDNumber>
#include <QGridLayout>
#include <QPushButton>
#include <QDebug>

calculator::calculator(QWidget *parent)
    : QWidget(parent)
{
    m_plcd = new QLCDNumber(12);
    m_plcd->setSegmentStyle(QLCDNumber::Flat);
    m_plcd->setMinimumSize(150, 50);

    QChar aButtons [4] [4] = {{'7', '8', '9', '/'},
                              {'4', '5', '6', '*'},
                              {'1', '2', '3', '-'},
                              {'0', '.', '=', '+'}
                             };

    QGridLayout* ptopLayout = new QGridLayout;
    ptopLayout->addWidget(m_plcd, 0, 0, 1, 4);


    ptopLayout->addWidget( new QPushButton("CE"), 1, 3);

    for (int i=0; i<4; ++i){
        for(int j=0; j<4; ++j){
            ptopLayout->addWidget(new QPushButton(aButtons[i][j]), i+2, j);
        }
    }
    setLayout(ptopLayout);
}

calculator::~calculator()
{

}

Правильно ли это будет?
Страниц: 1 ... 5 6 [7]

Страница сгенерирована за 0.074 секунд. Запросов: 23.