从外部类打印到MainWindow的元素
Printing to an element of MainWindow from an outside class
我已经创建了一组监视外部应用程序的观察程序/帮助程序类,我希望在进行更改时将这些类打印到MainWindow ui中的日志窗口中。我的想法是在main中的一个线程中创建这个观察程序,但我不确定将它链接到我的MainWindow的最佳方式。我知道简单地按照下面的方式传递它是行不通的,但由于Qt的设计,我不确定正确的方法来做到这一点,如果有的话。一些研究向我表明,将MainWindow传递给外部班级并不合适,但我不确定有更好的方法。
int main(int argc, char *argv[])
{
try {
std::string host = "localhost";
unsigned short port = 8193;
MainWindow w;
w.show();
// Access class for the program that I am watching
UserInterface ui(host, port);
// StatePrinter class, which is registered in the UI and will print changes to MainWindow, ideally
// would I be able to pass something in the StatePrinter constructor to accomplish my goal?
ui.registerObserver(new StatePrinter(w));
UiRunner runner(ui);
boost::thread runnerThread(boost::ref(runner));
w.show();
QApplication a(argc, argv);
runner.cancel();
runnerThread.join();
return a.exec();
} catch(std::exception &ex) {
// ...
}
}
我想在MainWindow中制作这个线程是有可能的,但我更喜欢在主窗口中使用它。将StatePrinter类链接到MainWindow的最佳方式是什么?
您可以使您的观察者类本身成为QObject,将其推送到线程中,并使其在"注意到"您想要记录的更改时发出信号,并将日志信息作为信号参数。
然后,您可以在QThread中按如下方式推送此对象:
QThread* thread = new QThread();
ui->moveToThread(thread);
//Create the needed connections
thread->start();
根据需要,您可以将信号连接到线程的start()
插槽,而不是直接调用它。(阅读本文,了解线程需要哪些连接,以便正确启动、停止和清理)。
您有几个问题:
- 在QApplication实例之前创建小部件
- runnerThread.join调用将在进入Qt事件循环之前阻塞主Qt线程,因此您的GUI将被冻结
您应该实现通知系统来监视boost线程的终止。但更好的解决方案是使用Qt线程。
- 您应该创建第一个类——具有必要信号的"观察者"
- 然后用UI逻辑和必要的插槽创建第二个类
- 然后将信号连接到插槽
- 利润
看看关于QThread的Qt文档——有一些简单的示例。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 从外部类打印到MainWindow的元素