在 Qt 中将多个小部件合并为一个

Combine multiple widgets into one in Qt(在 Qt 中将多个小部件合并为一个)

本文介绍了在 Qt 中将多个小部件合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中反复使用一对 QComboBoxQListWidget.它们的交互是高度耦合的——当在组合框中选择一个项目时,列表会以某种方式被过滤.我正在跨多个对话框实现复制粘贴这两个小部件之间的所有信号和插槽连接,我认为这不是一个好主意.

I'm repeatedly using a pair of QComboBox and QListWidget in a project. Their interaction is highly coupled - when an item is selected in the combo box, the list is filtered in some way. I'm copy pasting all the signal and slot connections between these two widgets across multiple dialog box implementation which I don't think is a good idea.

是否可以创建一个自定义小部件,它将容纳这两个小部件并将所有信号和插槽连接放在一个地方?如下所示:

Is it possible to create a custom widget, which will hold these two widgets and will have all signal and slot connection in one place? Something like as follows:

class CustomWidget
{
    QComboBox combo;
    QListWidget list;

    ...
};

我想将此小部件用作单个小部件.

I want to use this widget as a single widget.

推荐答案

通常的做法是继承QWidget(或QFrame).

The usual way of doing this is to sub-class QWidget (or QFrame).

class CustomWidget: public QWidget {
 Q_OBJECT

 CustomWidget(QWidget *parent)
  : QWidget(parent) {
    combo = new QComboBox(...);
    list  = new QListWidget(...);
    // create the appropriate layout
    // add the widgets to it
    setLayout(layout);
 }

 private:
  QComboBox *combo;
  QListWidget *list;

};

处理该自定义小部件中列表和组合之间的所有交互(通过将适当的信号连接到适当的插槽,可能为此定义您自己的插槽).

Handle all the interactions between the list and the combo in that custom widget (by connecting the appropriate signals to the appropriate slots, possibly defining your own slots for this).

然后,您可以通过专用信号和插槽公开自定义小部件的行为/API,可能会模仿列表和/或组合中的那些.

You then expose your custom widget's behavior/API through dedicated signals and slots, possibly mimicking the ones in the list and/or the combo.

地址簿教程将引导您完成所有这些,包括创建自定义小部件并为其定义信号和插槽.

The Address book tutorial walks you through all of that, including creating a custom widget and defining signals and slots for it.

这篇关于在 Qt 中将多个小部件合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Qt 中将多个小部件合并为一个

基础教程推荐