2016-03-23 41 views
0

我正在尝试做一个简单的测试,以使用用“Qt Design”制作的UI对象,但我对Qt和C++很新。 我有一个非常简单的用户界面:3 LineEdit和1点式按钮: IMAGE : the UI windowQt/C++:从另一个类获取Ui QLineEdit文本

我有这应该控制用户界面客户端类。它连接QPushButton,它应该从QLineEdit获取内容。 但结果在QDebug总是相同的,当我按下按钮,即使当我改变QLineEdit的领域:“客户端连接:‘’0”

而且,如果我用on_pushButton_clicked与QtDesign制成,它会显示QlineEdits的实际值。

为什么Qstrings总是一样的?我是否传递了初始对象的副本?如何解决这个问题?

是制作ViewController的好方法吗?否则,什么是好方法?

感谢您的帮助,

祝您有美好的一天!

Client.cpp

#include "client.h" 
#include "mainwindow.h" 
#include "logwindow.h" 

Client::Client() 
{ 
    LogWindow* w1 = new LogWindow(); 
    MainWindow* w2 = new MainWindow(); 

    _stack = new QStackedWidget(); 
    _stack->addWidget(w1); 
    connect(w1->getButton(),SIGNAL(clicked()),this,SLOT(connexion())); 

    _stack->addWidget(w2); 
    _stack->show(); 
} 

//When the button is Pushed, gets the content from QlineEdits and prints them 
void Client::connexion() 
{ 
    QString ip=(LogWindow (_stack->currentWidget())).getIP(); 
    int port=((LogWindow (_stack->currentWidget())).getPort()).toInt(); 

    socket = new QTcpSocket(this); 
    socket->connectToHost(ip, port); 

    _stack->setCurrentIndex((_stack->currentIndex()+1)%_stack->count()); 
    qDebug() <<"Client connected : " << ip << ":"<<port; 
} 

而被Qt自动进行类:

LogWindow.cpp

#include "logwindow.h" 
#include "ui_logwindow.h" 



LogWindow::LogWindow(QWidget *parent) : 
    QWidget(parent), 
    ui(new Ui::LogWindow) 
{ 
    ui->setupUi(this); 
} 

LogWindow::~LogWindow() 
{ 
    delete ui; 
} 


QPushButton* LogWindow::getButton() 
{ 
    return ui->pushButton; 
} 

QString LogWindow::getIP() 
{ 
    //LineEdit named "IP_text" 
    return ui->IP_text->text(); 
} 

QString LogWindow::getPort() 
{ 
    //LineEdit named "Port_text" 
    return ui->Port_text->text(); 
} 

LogWindow.h

namespace Ui { 
class LogWindow; 
} 

class LogWindow : public QWidget 
{ 
    Q_OBJECT 

public: 
    explicit LogWindow(QWidget *parent = 0); 
    ~LogWindow(); 
    QPushButton* getButton(); 
    QString getIP(); 
    QString getPort(); 

private slots: 
    void on_pushButton_clicked(); 

private: 
    Ui::LogWindow *ui; 
}; 
+0

在'Client :: connexion'中,您正在创建'LogWindow'的新实例。如果您想在其他'Client'的成员函数中访问它,则使'LogWindow * w1'成为'Client'类的成员变量。 – thuga

+0

非常感谢!我不知道我是如何错过的,我没有使用w1来获取IP .... 关于编程,像我是doiing一样管理界面是一件好事吗? – camb

+0

除了'_stack'是一个没有父项的组件,所以你必须确保在不再需要它的时候销毁它(例如调用析构函数中的'delete _stack;''' *)。大多数初学者会尝试使'ui'变量公开以从'IP_text'获取数据,但是您通过使用LogWindow :: getIP'函数正确执行了。 – thuga

回答

0

Thuga解决它:

在客户端::联接要创建LogWindow的新实例。 如果您希望 也可以在其他客户端的成员函数中访问它,使LogWindow * w1成为您的客户端类的成员变量。

没有太多抱怨,只是_STACK是一个小部件 没有父,所以你必须确保你摧毁它,当你不 需要它了(例如呼叫删除_STACK;在析构函数)。 大多数初学者会试图使公共变量从IP_text得到 数据,但是您做了正确的操作,通过使用LogWindow :: getIP函数来获得 。

如果你不希望暴露用户界面 - >按钮类之外,你 可以为您LogWindow类的信号,和用户界面 - >按钮的点击 信号连接到该信号。您可以将信号连接到 信号,它不一定是一个插槽。