简体   繁体   English

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

[英]Combine multiple widgets into one in Qt

I'm repeatedly using a pair of QComboBox and QListWidget in a project. 我在一个项目中反复使用一对QComboBoxQListWidget 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. 我想将此小部件用作单个小部件。

The usual way of doing this is to sub-class QWidget (or QFrame ). 通常的方法是子类QWidget (或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). 处理该自定义小部件中列表和组合之间的所有交互(通过将适当的信号连接到适当的插槽,可能为此定义您自己的插槽)。

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. 然后,您通过专用信号和插槽公开自定义窗口小部件的行为/ API,可能模仿列表和/或组合中的那些。

The Address book tutorial walks you through all of that, including creating a custom widget and defining signals and slots for it. 地址簿教程将指导您完成所有这些工作,包括创建自定义窗口小部件以及为其定义信号和插槽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM