Combine multiple widgets into one in Qt(在 Qt 中将多个小部件合并为一个)
问题描述
我在一个项目中反复使用一对 QComboBox
和 QListWidget
.它们的交互是高度耦合的——当在组合框中选择一个项目时,列表会以某种方式被过滤.我正在跨多个对话框实现复制粘贴这两个小部件之间的所有信号和插槽连接,我认为这不是一个好主意.
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 中将多个小部件合并为一个
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01