在Qt中将多个小部件组合成一个 [英] Combine multiple widgets into one in Qt

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

问题描述

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



是可能创建一个自定义窗口小部件,它将保存这两个小部件,并将所有的信号和插槽连接在一个地方?类似如下:

  class CustomWidget 
{
QComboBox combo;
QListWidget list;

...
};

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

QWidget (或 QFrame / code>)。

  class CustomWidget:public QWidget {
Q_OBJECT

CustomWidget(QWidget * parent)
:QWidget(parent){
combo = new QComboBox(...);
list = new QListWidget(...);
//创建适当的布局
//将小部件添加到它
setLayout(layout);
}

private:
QComboBox * combo;
QListWidget * list;

};

处理列表和组合框之间的所有交互(通过将适当的信号连接到



然后通过专用信号和插槽显示您的自定义窗口部件的行为/ API,可能模拟列表中的那些和/或组合。



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


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.

解决方案

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).

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中将多个小部件组合成一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆