7

I have a table that is basically a QTreeWidget and I want to put a clickable widget, possibly a button inside it. Each row is a QTreeWidgetItem, but I don't see how I can add a button with QTreeWidgetItem::setData

ulak blade
  • 2,515
  • 5
  • 37
  • 81
  • 2
    Consider using `QTreeWidget::setItemWidget()`. – vahancho Jul 09 '15 at 11:41
  • @vahancho the parent in the PushButton is the QTreeWidgetItem to which I'm setting it or the QTreeWidget? – ulak blade Jul 09 '15 at 11:48
  • `QTreeWidgetItem` cannot be a parent for a push button. You do not neet to set a parent, as documentation says: `"Note: The tree takes ownership of the widget."`. – vahancho Jul 09 '15 at 12:05

1 Answers1

8

Here is a modification to the example provided in Qt Documentation for QTreeWidget adding a QPushButton to the second item

 ui->treeWidget->setColumnCount(1);
 QList<QTreeWidgetItem *> items;
 for (int i = 0; i < 10; ++i)
    items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("item: %1").arg(i))));
 ui->treeWidget->insertTopLevelItems(0, items);

 ui->treeWidget->setItemWidget(items.value(1),0,new QPushButton("Click Me")); // Solution for your problem 

For two push buttons side by side within an item,you can take this approach

QWidget *dualPushButtons = new QWidget();
QHBoxLayout *hLayout = new QHBoxLayout();
hLayout->addWidget(new QPushButton("Button1"));
hLayout->addWidget(new QPushButton("Button2"));
dualPushButtons->setLayout(hLayout);

ui->treeWidget->setItemWidget(items.value(1),0,dualPushButtons);

You can adapt this by adding properties to the buttons etc.

techneaz
  • 998
  • 6
  • 9
  • thanks a lot, is it possible to have 2 buttons in one slot? Like two small buttons next to each other in a single slot/cell of the table? – ulak blade Jul 09 '15 at 12:04
  • You can create a custom widget with two push buttons with an arrangement(layout) you want and instead of the QPushButton in the above solution, you can add that widget `ui->treeWidget->setItemWidget(items.value(1),0,widgetWithTwoButtons);` – techneaz Jul 09 '15 at 12:07
  • Can this be done purely programatically or must I use the UI designer? – ulak blade Jul 09 '15 at 12:09
  • @ulakblade [This might be helpful to you in your quest.](http://doc.qt.io/qt-4.8/designer-creating-custom-widgets.html) – MildWolfie Jul 09 '15 at 12:16
  • @ulakblade Find the edited answer for two pushbutton in one item. Please edit your question accordingly – techneaz Jul 09 '15 at 12:24
  • @techneaz how will you get complete row if any of the two added button clicked? My Treewidget is hvaing 4 column and 4th column is having 2 buttons. Now, If I click either of the button then I want to display data of col1, col2, col3 of same row? could you please help? – Saurabh Jan 08 '23 at 20:39