Why can't I get the text out of a QTableWidget cell? - qt

I have searched the answer, and ui->tableWidget->item( row, col )->text(); seems to be the answer.
Now, in my code I have:
ui-> tableWidget->setItem(row-1, 1, new QTableWidgetItem("clicked"));
This works just fine. When the cell is clicked, it displays the "clicked" message. BUT, when i add this below:
QString str;
QTableWidgetItem * itm = ui->tableWidget->item( 3, 1 );
str = itm->text();
The program crashes.
Any idea how could I view the text from the cell?
All the code.Constructor:
{
ui->setupUi(this);
QDate date = QDate::currentDate();
QString dateString = date.toString();
QFont myFont;
QFontMetrics font_meter(myFont);
int line_width=0;
ui->label->setText(dateString);
QFile file(":/input.txt");
if(!file.open(QIODevice::ReadOnly))
{
QMessageBox::information(0,"info",file.errorString());
}
QTextStream in(&file);
QStringList headerLabels;
QStringList rowLabels;
QStringList rowContents;
headerLabels << "Tasks to do" ;
int row_count=0;
while (true)
{
QString line = in.readLine();
if (line.isNull())
{
file.close();
break;
}
else
{
row_count++;
rowLabels.append(QString("%1").arg(row_count));
rowContents.append(line);
if( font_meter.width(line)>line_width)
{
line_width=font_meter.width(line);
}
}
}
ui->tableWidget->setRowCount(row_count);
ui->tableWidget->setVerticalHeaderLabels(rowLabels);
ui->tableWidget->setColumnCount(1);
// ui->tableWidget->setCellWidget();
for(int i=0;i<row_count;i++)
{
ui-> tableWidget->setItem(i-1, 1, new QTableWidgetItem(rowContents.at(i)));
}
}
slot:
void MainWindow::on_tableWidget_cellDoubleClicked(int row, int column)
{
ui->pushButton->setText( QString("%1").arg(row));
ui-> tableWidget->setItem(row-1, 1, new QTableWidgetItem("clicked"));
QString str;
QTableWidgetItem * itm = ui->tableWidget->item( 3, 1 );
str = itm->text();
}
I have tried to make another program.Just with a simple table and getting the text out of a cell:
ui->setupUi(this);
ui->tableWidget->setItem(1,1,new QTableWidgetItem("lol"));
QString str= ui->tableWidget->item(1,1)->text();
.Exactly the same error

ui->setupUi(this);
ui->tableWidget->setRowCount(1);
ui->tableWidget->setColumnCount(1);
ui->tableWidget->setItem(0, 0, new QTableWidgetItem("Hello World!"));
QTableWidgetItem *temp = ui->tableWidget->item(0, 0);
QString str = temp->text();
Works for me, I only managed to crash the program when rowCount or columntCount were 0.

Related

Qt QCompleter do not pop out

Problem description
  I want to be able to recognize the corresponding Chinese person name and complete the prompt by entering a short Chinese phonetic alphabet.
  For example, I have a map (("lvbu", "吕布"), ("lvbuwei", "吕不韦")) , then enter "lv" or "bu",The completer should pop up "吕布" and "吕不韦", but it seems that the stringlist must contain the content currently being entered to complete the prompt. The completer cannot recognize the mapping relationship.
  How can I solve it? I can hardly find a solution on the Internet because it involves Chinese.
My code
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Pinyin2Hanzi/myPinyin.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QString N = "吕布 吕不韦 南宫问天";
QStringList Names = N.split(" ");
// qDebug() << Names;
ui->comboBox->addItem("");
ui->comboBox->addItems(Names);
ui->comboBox->lineEdit()->setClearButtonEnabled(true);
CreateCompleter(Names, ui->comboBox->lineEdit());
ui->comboBox->setMaxCount(ui->comboBox->count()); //这行代码可以防止按回车键自动往combobox里addItem
}
MainWindow::~MainWindow()
{
delete ui;
}
std::map<std::string, std::vector<QString>> pinyin2NameMap; // This is a private variable
// 把所有人名按照拼音分类并存入map中
void MainWindow::PreparePinyinData(const QStringList &names)
{
for (auto & name : names)
{
QString outFristPy,outFullPy;
getComPingyinForStr(name, outFristPy, outFullPy);
// QString pinyin = GetPinyin(name);
QString pinyin = outFullPy;
// qDebug() <<"FristPy:" << outFristPy << "FullPy:" << outFullPy;
// qDebug() <<"pinyin:" << pinyin;
// QString fist, last;
// myNameSplit(name, last, fist); // 自动切分 [姓、名]
// last = getNamePingyin(last, true); // 获取 [姓] 的拼音
// fist = getNamePingyin(fist, false);// 获取 [名] 的拼音
// qDebug() << name + " : " + last + " " + fist << endl;
pinyin2NameMap[pinyin.toStdString()].push_back(name);
}
}
// 根据输入的拼音进行匹配并获取提示列表
QStringList MainWindow::GetMatchByPinyin(const QString &pinyin)
{
QStringList result;
if("" == pinyin.trimmed()){
return QStringList();
}
for (const auto & iter : pinyin2NameMap){
if (iter.first.find(pinyin.toStdString()) != std::string::npos){
auto vec = iter.second;
for(const auto & name : vec){
result.append(name);
}
}
}
return result;
}
// 创建QCompleter并设置自动补全模型
void MainWindow::CreateCompleter(const QStringList &names, QLineEdit *lineEdit)
{
PreparePinyinData(names);
QStringListModel *model = new QStringListModel(names);
QCompleter *completer = new QCompleter(model, lineEdit);
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setFilterMode(Qt::MatchContains);
completer->setCompletionMode(QCompleter::PopupCompletion);
lineEdit->setCompleter(completer);
connect(lineEdit, &QLineEdit::textEdited, [this,completer,lineEdit, model](const QString &text)
{
QStringList matchList = GetMatchByPinyin(text);
qDebug() << "listmodel:" << matchList;
// QString N = "lv不bu 可lvbuwei nan够gongwentian";
// QStringList matchList = N.split(" ");
model->setStringList(matchList);
completer->setModel(model);
completer->complete();
});
}

Get error messages when using QPrinter, QPainter and QTextDocument together

In my Qt application, I want to create a preview page with the content that contains the Header, Footer title and a TableView.
This is the code I used:
void MainWindow::print(QPrinter *printer)
{
int xscale = 50;
int yscale = 30;
QPoint top_left = QPoint(xscale, yscale);
QPoint top_right = QPoint(xscale + 552, yscale + 20);
QPoint bottom_left = QPoint(xscale, yscale + 1020);
QPoint bottom_right = QPoint(xscale + 492, yscale + 1020);
QPainter painter(printer);
painter.setRenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing |
QPainter::SmoothPixmapTransform, true);
// Header
painter.setFont(QFont("Arial", 10));
painter.drawImage(top_left, QImage(":/images/images/logo.png"));
painter.drawText(top_right, "Header");
// Print the Table
QString strStream;
QTextStream out(&strStream);
out << "<html>\n"
"<head>\n"
"<meta content=\"text/html; charset=utf-8\">\n"
"<title>Demo MyTableView</title>\n"
"<style tyle=\"text/css\">th{font-size: 14pt}\n td{font-size: 12pt}\n table td + td + td + td{font-weight:bold}</style>"
"</head>\n"
"<body bgcolor=#ffffff link=#5000A0>\n"
"<table cellspacing=\"0\" cellpadding=\"2\" border=\"1\" width=\"100%\">\n";
// Print the headers
out << "<thead><tr bgcolor=\"#ffffff\">";
for (int column = 0; column < columnCount; column++)
if (!myTableView->isColumnHidden(column))
out << QString("<th>%1</th>").arg(myTableView->model()->headerData(column, Qt::Horizontal).toString());
out << "</tr></thead>\n";
// Print the data
for (int row = 0; row < rowCount; row++) {
out << "<tr>";
for (int column = 0; column < columnCount; column++) {
if (!myTableView->isColumnHidden(column)) {
QString data = myTableView->model()->data(myTableView->model()->index(row, column)).toString().simplified();
out << QString("<td bkcolor=0 align=center>%1</td>").arg((!data.isEmpty()) ? data : QString(" "));
}
}
out << "</tr>\n";
}
out << "</table>\n"
"</body>\n"
"</html>\n";
QTextDocument *document = new QTextDocument();
document->setHtml(strStream);
document->print(printer); // I got the error messages at here
delete document;
// Footer
painter.setFont(QFont("Arial", 10));
painter.drawText(bottom_left, "Copyright 2013");
// Get current date and time
QDateTime dateTime = QDateTime::currentDateTime();
QString dateTimeString = dateTime.toString();
painter.drawText(bottom_right, dateTimeString);
}
When I run the application, I only see Header and Footer title in the preview page, the TableView is not shown. Then I used qDebug() to check and I got the error messages
QPrinter::setDocName: Cannot be changed while printer is active
QPainter::begin: A paint device can only be painted by one painter at a time.
at the line
document->print(printer);
How can I solve this issue to print the data normally with the Header, Footer title and TableView?
Thanks for your help!
Well, if Qt complains about using multiple painters at a time, make it use only one:) In other words, just split the code in your MainWindow::print() function into the smaller routines for each part of your document:
void MainWindow::drawHeader(QPrinter *printer)
{
QPainter painter(printer);
// .. Draw the header
[..]
}
void MainWindow::drawFooter(QPrinter *printer)
{
QPainter painter(printer);
painter.setFont(QFont("Arial", 10));
painter.drawText(bottom_left, "Copyright 2013");
[..]
}
void MainWindow::drawTable(QPrinter *printer)
{
QTextDocument document;
document.print(printer);
[..]
}
And finally:
void MainWindow::print(QPrinter *printer)
{
// Init something.
drawHeader(printer);
drawTable(printer);
drawFooter(printer);
[..]
}

Passing QRadioButton value from one window to another window in Qt (no matching function for call to)

I want to pass selected QRadioButton's value from one Window to another. I am confused with the function declaration to accept the text value in Second Window, here is my code.
Window1.cpp
void SelectOS :: processNextButton(){
if(ui->win32->isChecked()){
QString loc = "WIN/32Bit";
SelectSoftware *ss = new SelectSoftware (loc);
this->hide();
ss->show();
}
else
{
//QMessageBox:warning();
}
}
Window2.h
public:
SelectSoftware(const QString &text, QWidget *parent=0);
Window2.cpp
SelectSoftware::SelectSoftware(const QString &text, QWidget *parent):QMainWindow(parent),ui(new ui::SelectSoftware)
{
QString softpath = text;
qDebug << softpath;
}
But when I call
ss = new SelectSoftware();
or
ss= new SelectSoftware(const QString &text, QWidget *parent);
in Window2.cpp, I get the error : no matching function for call to SelectSoftware::SelectSoftware()
Where am I wrong?
UPDATE
Window2.cpp
#include "selectsoftware.h"
#include "ui_selectsoftware.h"
SelectSoftware *ss;
QStringList selectedModuleList;
SelectSoftware::SelectSoftware(const QString &text, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SelectSoftware)
{
ui->setupUi(this);
softpath = text;
setWindowPosition();
getSoftwareDetails();
initializeUi();
}
SelectSoftware::~SelectSoftware()
{
delete ui;
}
void SelectSoftware::setWindowPosition()
{
QDesktopWidget *desktop = QApplication::desktop();
int x = (desktop->width() - size().width())/2;
int y = (desktop->height() - size().height())/2;
move(x, y-50);
setFixedSize(size().width(), size().height());
}
void SelectSoftware::cancel()
{
qApp->exit(0);
}
void SelectSoftware::showMainPage()
{
ss = new SelectSoftware(softpath); // here its creating problem, not going forward and app is crashing!!!
for(int j = 0; j < softwareList.size(); j++){
if(checkBox[j]->isChecked()){
if(!comboBox[j]->currentIndex()){
QMessageBox::warning(this, "Select version !", "Select version number for all selected software");
return;
}
}
}
for(int i = 0; i < softwareList.size(); i++){
if(checkBox[i]->isChecked()){
ss->selectedSoftList.push_back(checkBox[i]->text());
ss->selectedVerList.push_back(comboBox[i]->currentText());
}
}
if(!ss->selectedSoftList.size()){
QMessageBox::warning(this, "No product Selected !", "Select one");
return;
}
else{
SelectionPage* sp = new SelectionPage;
this->hide();
sp->show();
}
}
void SelectSoftware::test(const int id)
{
if(checkBox[id]->isChecked()){
comboBox[id]->setEnabled(true);
comboBox[id]->addItem(" Select anyone ");
QString path = qApp->applicationDirPath() + "/products/" + checkBox[id]->text();
QDir dir;
dir.cd(path);
dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); ++i) {
QFileInfo fileInfo = list.at(i);
comboBox[id]->addItem(fileInfo.fileName());
}
}else{
comboBox[id]->clear();
comboBox[id]->setDisabled(true);
}
}
void SelectSoftware::getSoftwareDetails()
{
QString fileName = qApp->applicationDirPath() + "/abc/" + SOFTWARELIST;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
QString msg = "Could not find the file " + fileName;
errorExit(msg);
}
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine();
processLine(line.toLower());
}
}
void SelectSoftware::processLine(QString str)
{
QStringList list = str.split(",");
QDir path = qApp->applicationDirPath() + "/products/" + list[0];
if(path.exists() && (list.size() == 2)){
QString tmp = list[0];
tmp = tmp.toLower();
softwareList.push_back(tmp);
}
}
void SelectOption::initializeUi()
{
this->setWindowTitle("Window2");
QGridLayout *gridLayout1 = new QGridLayout();
gridLayout1->setMargin(5);
gridLayout1->setSpacing(5);
QSignalMapper* signalMapper = new QSignalMapper();
for(int i = 0; i < list.size(); i++){
radioButton[i] = new QRadioButton();
radioButton[i]->setText(softwareList[i]);
signalMapper->setMapping(radioButton[i], i);
gridLayout1->addWidget(radioButton[i], i/1, i%1);
connect(radioButton[i], SIGNAL(clicked()),signalMapper, SLOT(map()));
}
connect(signalMapper, SIGNAL(mapped(const int &)),this, SIGNAL(radioChecked(const int &)));
connect(this, SIGNAL(radioChecked(const int &)),this, SLOT(test(const int)));
QGridLayout *gridLayout2 = new QGridLayout();
gridLayout2->setMargin(5);
gridLayout2->setSpacing(5);
for(int j = 0; j < list.size(); j++){
comboBox[j] = new QComboBox();
comboBox[j]->setDisabled(true);
gridLayout2->addWidget(comboBox[j], j/1, j%1);
}
QPushButton *nextButton = new QPushButton("Next >");
nextButton->setDefault(true);
connect(nextButton, SIGNAL(clicked()), this, SLOT(showMainPage()));
QPushButton *backButton = new QPushButton("< Back");
backButton->setDefault(true);
connect(backButton, SIGNAL(clicked()), this, SLOT(showSelectOS()));
QPushButton *cancelButton = new QPushButton("Cancel");
cancelButton->setDefault(true);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));
QHBoxLayout *hboxlayout;
hboxlayout = new QHBoxLayout();
hboxlayout->addLayout(gridLayout1);
hboxlayout->addLayout(gridLayout2);
QHBoxLayout *layout;
layout = new QHBoxLayout();
layout->addStretch(10);
layout->addWidget(nextButton);
layout->addWidget(backButton);
layout->addWidget(cancelButton);
layout->addStretch(10);
QVBoxLayout *mainLayout;
mainLayout = new QVBoxLayout();
mainLayout->addLayout(hboxlayout);
mainLayout->addLayout(layout);
ui->centralwidget->setLayout(mainLayout);
}
QVector<QString> SelectSoftware::getSelectedSoftware()
{
return ss->selectedSoftList;
}
QVector<QString> SelectSoftware::getSelectedVersion()
{
return ss->selectedVerList;
}
QStringList SelectSoftware::getSelectedModules()
{
return selectedModuleList;
}
First of all - use signals and slots, Luke
Second of all, you cannot call ss = new SelectSoftware();, since you haven't declared SelectSoftware constructor without parameters, and calling ss= new SelectSoftware(const QString &text, QWidget *parent); is illegal in C++.
SelectSoftware *ss = new SelectSoftware (loc); is correct, though.
1. In void SelectSoftware::processLine(QString str) addressing to list[0] without checking that list is not empty might be dangerous. I recomend you to add:
if (!list.size())
return;
right after initialization.
2. In void SelectOption::initializeUi() what is list? Are you sure list.size() <= softwareList.size()? If not, it's a potential problem.
3. What is radioButton? I don't see it's initialization. If it is QList < QRadioButton * >, than radioButton[i] = new QRadioButton(); is a bad one and you should do this:
radioButton.append(new QRadioButton());
4. Same goes to comboBox.
Each of the list can cause the crash of your application. And I could easily miss something.

How to select child's items checkBoxs in QTreeView when select their parent's checkbox

I want to select/unselect all child's items QCheckBoxs when I select/unselect their parent's item QCheckBox.
i inherit from QTreeView and detect when the QCheckBox is selected then i call function to do selecting/unselecting process.
here my code:
#ifndef MYQTREEVIEW_H
#define MYQTREEVIEW_H
#include <QTreeView>
#include <QMouseEvent>
#include <QDebug>
#include <QStandardItem>
class MyQTreeView: public QTreeView {
public:
MyQTreeView(QWidget* parent=0): QTreeView(parent){}
virtual ~MyQTreeView() {}
protected:
void resettingCheckBox (QModelIndex& parentIndex) {
if ( ! parentIndex.isValid() )
return;
QString text = parentIndex.data( Qt::DisplayRole ).value<QString>();
qDebug() << "parent is: " << text;
if ( model()->hasChildren(parentIndex) ) {
for( int i = 0; i < model()->rowCount(parentIndex) ; i++ ) {
QModelIndex childIndex = model()->index( i, 0, parentIndex );
if ( model()->hasChildren(childIndex) )
resettingCheckBox(childIndex);
else {
QString text = childIndex.data( Qt::DisplayRole ).value<QString>();
qDebug() << "child is: " << text;
QStandardItem *parentItem = static_cast<QStandardItem*> (parentIndex.internalPointer());
QStandardItem *childItem = static_cast<QStandardItem*> (childIndex.internalPointer());
if ( parentItem->checkState() == Qt::Checked ) {
qDebug() << "child item " << childItem->checkState();
childItem->setCheckState( Qt::Unchecked);
}
else {
qDebug() << "child item " << childItem->checkState();
childItem->setCheckState( Qt::Checked);
}
}
}
}
}
void mousePressEvent (QMouseEvent *event) {
QModelIndex index = indexAt(event->pos());
if(index.isValid()) {
QStyleOptionButton opt;
opt.QStyleOption::operator=(viewOptions());
opt.rect = visualRect(index);
QRect rect = style()->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt);
if (rect.contains(event->pos())) {
resettingCheckBox(index);
}
QTreeView::mousePressEvent(event);
}
}
};
#endif // MYQTREEVIEW_H
the code is not working probably when i select/unselect parent checkBox (subchilds is not selected/unselected).
Thanks in advance.
I believe the best way to manipulate treeview items is through the model. It looks like you're using QStandardItemModel; so you can override your model's setData method and reset child items values for the item index passed as a parameter to this method. Below is a small example:
class TestModel : public QStandardItemModel
{
public:
TestModel() {}
bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole)
{
QStandardItem *item = itemFromIndex(index);
for( int i = 0; i < item->rowCount() ; i++ )
{
QStandardItem *childItem = item->child(i);
setData(childItem->index(), value, role);
}
return QStandardItemModel::setData(index, value, role);
}
};
here's how this model gets initialized:
QStandardItemModel* tableModel = new TestModel();
QStandardItem* parentItem = tableModel->invisibleRootItem();
for (int i = 0; i < 4; ++i)
{
QStandardItem *item = new QStandardItem(QString("item %0").arg(i));
item->setCheckable(true);
parentItem->appendRow(item);
parentItem = item;
}
treeView->setModel(tableModel);
hope this helps, regards
It seems to me that you should call QTreeView::mousePressEvent(event) before resettingCheckBox(index), to let QTreeView update the checkState.
override mouseReleaseEvent() instead of mousePressEvent()!
because the checkState changes when mouse Release not mouse - press!

QComboBox inside QTreeWidgetItem

Is there something similar to the (PyQT)
QTreeWidgetItem.setCheckState(0, Qt.Checked) but for the combo box?
I can't see anything in the reference, so how can I insert a custom QComboBox as one of the elements within QTreeWidgetItem?
Use QTreeWidget::setItemWidget ( QTreeWidgetItem * item, int column, QWidget * widget ) to put the combo box into the cells.
For example, let's make all rows of the second column of a 2-column QTreeWidget to all be combo boxes:
QTreeWidgetItemIterator it(ui->treeWidget);
while (*it) {
QComboBox *comboBox = new QComboBox(this);
comboBox->addItems(QStringList() << "item1" << "item2");
ui->treeWidget->setItemWidget(*it, 1, comboBox);
++it;
}
Our example widget now looks like this:
I know this is an old question but I think I have a more thorough answer. To get any functionality out of the QComboBox, you'll probably need to subclass it. Here's the solution that I came up with:
#ifndef COMBOBOXITEM_H
#define COMBOBOXITEM_H
#include
class ComboBoxItem : public QComboBox
{
Q_OBJECT
private:
QTreeWidgetItem *item;
int column;
public:
ComboBoxItem(QTreeWidgetItem*, int);
public slots:
void changeItem(int);
};
ComboBoxItem::ComboBoxItem(QTreeWidgetItem *item, int column)
{
this->item = item;
this->column = column;
connect(this, SIGNAL(currentIndexChanged(int)), SLOT(changeItem(int)));
}
void ComboBoxItem::changeItem(int index)
{
if(index >=0)
{
item->setData(this->column, Qt::UserRole, this->itemText(index));
qDebug() item->data(this->column, Qt::UserRole).toString();
}
}
#include "moc_ComboBoxItem.cpp"
#endif // COMBOBOXITEM_H
////// Sample implementation..
lst = new QTreeWidget;
// Snip
QTreeWidgetItem *itm = new QTreeWidgetItem;
// Snip
ComboBoxItem *cmb = new ComboBoxItem(itm, 1);
cmb->addItem("One");
cmb->addItem("Two");
cmb->addItem("Three");
cmb->addItem("Four");
lst->setItemWidget(itm, 1, cmb);
I hope that helps someone in need of a QComboBox inside of a QTreeWidgetItem!
Use
setItemWidget(QTreeWidgetItem( ), column, QWidget( ) )
.Just add your QComboBox() as a parameter, as it inherits QWidget() so it is compatible.
tree = QTreeWidget()
cmb = QComboBox()
cmb.addItem("Item1", 'value1')
cmb.addItem("Item2", 'value2')
cmb.addItem("Item3", 'value3')
item = QTreeWidgetItem(tree.invisibleRootItem())
column = 0
item.setData(column, Qt.EditRole, 'NameYouWant')
column += 1
tree.setItemWidget(item, column , cmb)
Here is small fix to the another posters method. I found that is uses Data to update the box How ever I made small change to setText updater for the method.
#ifndef COMBOBOXITEM_H
#define COMBOBOXITEM_H
#include <QtGui>
class ComboBoxItem : public QComboBox
{
Q_OBJECT
private:
QTreeWidgetItem *item;
int column;
public:
ComboBoxItem(QTreeWidgetItem*, int);
public slots:
void changeItem(int);
};
ComboBoxItem::ComboBoxItem(QTreeWidgetItem *item, int column)
{
this->item = item;
this->column = column;
connect(this, SIGNAL(currentIndexChanged(int)), SLOT(changeItem(int)));
}
void ComboBoxItem::changeItem(int index)
{
if(index >=0)
{
this->item->setText(this->column, this->currentText());
}
}
#include "moc_ComboBoxItem.cpp"
#endif // COMBOBOXITEM_H
////// Sample implementation..
lst = new QTreeWidget;
// Snip
QTreeWidgetItem *itm = new QTreeWidgetItem;
// Snip
ComboBoxItem *cmb = new ComboBoxItem(itm, 1);
cmb->addItem("One");
cmb->addItem("Two");
cmb->addItem("Three");
cmb->addItem("Four");
lst->setItemWidget(itm, 1, cmb);
This is easiest method:
QComboBox *cb = new QComboBox(this);
QStringList cbTexts;
cbTexts << tr("First") << tr("Second") << tr("Third");
cb->addItems(cbTexts);
QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
ui->treeWidget->addTopLevelItem(item);
ui->treeWidget->setItemWidget(item, [colum here], cb);
for (int col = 0; col < [num colums]; ++col) ui->treeWidget->resizeColumnToContents(col);

Resources