0

I have a project on serial communications using Qt. This is very easy because I use QSerialDevice. The problem is making multiple forms to be accessed by QSerialDevice.

For example I have 2 forms, form1 and form2. I try to send data over the last hyperterminal to be displayed in form1 (done), but it cannot be displayed in form2. Not only that, but I want to be able to do port->write through form2.

My question is: can we use QSerialDevice2.0 with multiple .cpp files and multiple forms?

4

2 回答 2

2

而不是 QSerialDevice 使用更好的 QtSerialPort http://qt-project.org/wiki/QtSerialPort

于 2012-06-20T06:59:35.863 回答
1

据我所知,您想要做的是有 2 种不同的 UI 表单,可用于将数据发送到串行端口。我目前正在为一个项目解决一个几乎相同的问题,而我为我工作的是使用MVC风格的架构来解决这个问题。

有一个控制器,它知道显示哪种形式并可以访问 QSerialDevice。然后表单可以发出一个void write(QByteArray)信号,该信号将连接到控制器上负责写入端口的插槽。

class Form1 : QWidget {
public:
  Form1();
  ~Form1();
  //some form1 stuff.
signals:
  void writeToPort(QByteArray);
}
class Form2 : QWidget {
public:
  Form2();
  ~Form2();
  //Do some form2 stuff
signals:
  void writeToPort(QByteArray);
}


class Controller : QObject {
 public:
   Controller();
   ~Controller();
 public slots:
   void writeRequested(QByteArray data);
 private:
   Form1* view;
   Form2* otherView;
   QSerialDevice* port;
 }


 Controller::Controller()
 {
    view = new Form1();
    connect(view, SIGNAL(writeToPort(QByteArray)),this,SLOT(writeRequested(QByteArray data)));
    otherView = new Form2();
    connect(otherView, SIGNAL(writeToPort(QByteArray)),this,SLOT(writeRequested(QByteArray data)));
    port = new QSerialDevice();
    port->open();
 }

Controller::writeRequested(QByteArray data)
{
   if (port && port->isOpen())
   {
      port->write(data);
   }
}

可以有其他方法来处理控制器中表单之间的连接和切换。通过使用信号和插槽,类之间的耦合将减少,您不必担心串行端口代码会堵塞您的 UI。

于 2012-06-18T13:40:07.263 回答