Qt中添加控件为什么使用指针?

Qt中添加控件为什么使用指针?

Qt中使用控件时(如按钮),需要定义其指针变量,并为其指定父类指针,原因如下:

  • 控件直接添加到父类容器中。
  • 父类容器一般没有直接添加控件的接口。

示例程序如下

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    //定义指针变量
    QPushButton* btn=new QPushButton(this);
    btn->setText("11111");
}

总结

  • 相对来说,可以使用对象的地方尽量使用对象(这种方式安全)。
  • 如需动态分配内存,请使用指针变量。
  • 对于自定义类型,肯能存在交叉引用,请使用指针变量。
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt ,可以通过自定义 QHeaderView 来实现在表头添加控件的功能。具体步骤如下: 1. 定义一个继承自 QHeaderView 的子类,例如 MyHeaderView。 2. 在 MyHeaderView 重写 paintSection() 函数,该函数会在绘制表头时被调用。 3. 在 paintSection() 函数,首先调用父类的 paintSection() 函数,然后在需要添加控件的位置进行控件的绘制。 以下是一个添加 QPushButton 控件的例子: ```cpp class MyHeaderView : public QHeaderView { public: MyHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr) : QHeaderView(orientation, parent) { } protected: void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const override { // 调用父类的 paintSection() 函数 QHeaderView::paintSection(painter, rect, logicalIndex); // 在第一列表头的右侧绘制一个 QPushButton if (logicalIndex == 0) { QPushButton button("Button", const_cast<QWidget*>(static_cast<const QWidget*>(parent()))); QRect buttonRect = QRect(rect.right() - 20, rect.top() + 2, 18, 18); // 控件的位置和大小 button.setGeometry(buttonRect); button.show(); } } }; ``` 使用时,将表格的水平表头和垂直表头分别设置为 MyHeaderView 类的实例即可: ```cpp QTableWidget table; table.setHorizontalHeader(new MyHeaderView(Qt::Horizontal, &table)); table.setVerticalHeader(new MyHeaderView(Qt::Vertical, &table)); ``` 注意:由于 QPushButton 控件是在 paintSection() 函数创建的,因此需要使用 const_cast 和 static_cast 将 parent 指针转换为非 const 类型。同时,由于 QPushButton 控件是在 MyHeaderView 的生命周期内创建的,因此需要在 paintSection() 函数设置其位置和大小,并在 paintSection() 函数之外手动调用其 show() 函数显示控件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值