I'm having problems with my QTableView and QItemDelegate classes. For one column my delegate creates a simple combo box and everything works just fine. For my 2nd column I need a widget that has two combo boxes in a single widget.
I've written the following code in my QItemDelegate, just to be clear this only shows code for my 2nd column, the one that doesn't work. The other simple Combo-box isn't shown as it works fine:
QWidget *UserDefinedUnitsDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem & option ,const QModelIndex & index ) const
{
//set up a simple widget with a layout
QWidget* pWidget = new QWidget(parent);
QHBoxLayout* hLayout = new QHBoxLayout(pWidget);
pWidget->setLayout(hLayout);
//add two combo boxes to the layout
QComboBox* comboEditor = new QComboBox(pWidget);
QComboBox* comboEditor2 = new QComboBox(pWidget);
//now add both editors to this
hLayout->addWidget(comboEditor);
hLayout->addWidget(comboEditor2);
return pWidget;
}
Now this displays just fine but when I edit it and click elsewhere it doesn't stop editing. Can anyone offer any pointers?
Edit: So i need to call CommitData() and closeEditor() at some point. Can anyone offer pointers on where to call these?
Thanks.
You can keep the editor widget as a member of class and emit commitData when the current index of one of the comboboxes has changed. So you can connect currentIndexChanged(int) to a slot and emit commitData from there:
QWidget *UserDefinedUnitsDelegate::createEditor(QWidget *parent,const QStyleOptionViewItem & option ,const QModelIndex & index ) const
{
//set up a simple widget with a layout
pWidget = new QWidget(parent);
QHBoxLayout* hLayout = new QHBoxLayout(pWidget);
pWidget->setLayout(hLayout);
//add two combo boxes to the layout
QComboBox* comboEditor = new QComboBox(pWidget);
QComboBox* comboEditor2 = new QComboBox(pWidget);
connect(comboEditor,SIGNAL(currentIndexChanged(int)),this,SLOT(setData(int)));
connect(comboEditor2,SIGNAL(currentIndexChanged(int)),this,SLOT(setData(int)));
//now add both editors to this
hLayout->addWidget(comboEditor);
hLayout->addWidget(comboEditor2);
return pWidget;
}
void UserDefinedUnitsDelegate::setData(int val)
{
emit commitData(pWidget);
}
Related
I have an editable list view inside a dock widget. I wanted to keep the track of the data before the user edits and the data after the user edits. The complete concerning code is:
void MainWindow :: createDock()
{
//initialize dockWidget
QDockWidget *dock = new QDockWidget("Tags", this);
dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
dock->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable);
//widget to store all widgets placed inside dock because dock cannot set layout but can set widget
QWidget *tags = new QWidget(dock);
//initiazlize treeViewModel
listViewModel = new QSqlTableModel(this);
listViewModel->setTable("tags");
listViewModel->select();
listViewModel->setHeaderData(0, Qt::Horizontal, "Tags");
//set the model for treeView
listView = new QListView(dock);
listView->setModel(listViewModel);
connect(listView, &QListView::doubleClicked, this, &MainWindow::onListViewDoubleClicked, Qt::UniqueConnection);
connect(listViewModel, &QSqlTableModel::dataChanged, this, &MainWindow::onLVDataChanged, Qt::UniqueConnection);
//add treeView to the dock
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(listView);
tags->setLayout(layout);
//add the dock widget to the main window and show it
dock->setWidget(tags);
this->addDockWidget(Qt::LeftDockWidgetArea, dock);
//dock->show();
}
void MainWindow :: onLVDataChanged(const QModelIndex& index, const QModelIndex& index2, const QVector<int> & roles)
{
QMetaMethod metaMethod = sender()->metaObject()->method(senderSignalIndex());
QMessageBox::information(this, "", metaMethod.name());
afterUpdate = index.data().toString();
//do somethings
beforeUpdate = "";
afterUpdate = "";
}
void MainWindow :: onListViewDoubleClicked(const QModelIndex &index)
{
QMetaMethod metaMethod = sender()->metaObject()->method(senderSignalIndex());
QMessageBox::information(this, "", metaMethod.name());
beforeUpdate = index.data().toString();
}
I do this:
I double click an item so as to edit it. The onDoubleClick() is called only once (seen becuase of QMessageBox). I add a space to the data present (in my case it was "fiction", i changed it to "fiction "). But, after I press enter, dataChanged() is called twice (again seen through QMessageBox).
I don't emit the signal explicitly. It is emitted only by model.
The problem is caused by the editing strategy, by default it is QSqlTableModel::OnRowChange, this expects the row to be changed emitting a signal to update the item and another to update the entire row, that can be easily seen if we use the following:
void MainWindow::onListViewDoubleClicked(const QModelIndex &index)
{
qDebug()<<__FUNCTION__<<index;
}
void MainWindow::onLVDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles)
{
qDebug()<<__FUNCTION__<<topLeft<<bottomRight<<roles<<topLeft.data();
}
Output:
onListViewDoubleClicked QModelIndex(1,0,0x0,QSqlTableModel(0x562940043670))
onLVDataChanged QModelIndex(1,0,0x0,QSqlTableModel(0x562940043670)) QModelIndex(1,0,0x0,QSqlTableModel(0x562940043670)) QVector() QVariant(QString, "tag2 ")
onLVDataChanged QModelIndex(1,0,0x0,QSqlTableModel(0x562940043670)) QModelIndex(1,2,0x0,QSqlTableModel(0x562940043670)) QVector() QVariant(QString, "tag2 ")
The solution is to change the editing strategy to QSqlTableModel::OnManualSubmit:
...
listViewModel = new QSqlTableModel(this);
listViewModel->setTable("tags");
listViewModel->setEditStrategy(QSqlTableModel::OnManualSubmit); // <--
listViewModel->select();
listViewModel->setHeaderData(0, Qt::Horizontal, "Tags");
...
I am trying to make a QTreeWidget such that each row contains a series of comboboxes. Depending on how the user interacts with the comboboxes I would like certain comboboxes to becomes line edits and some to become buttons.
It was suggested here that a QStackedWidget would serve my needs and its done a pretty good job except now I need a way to alter the QStackedWidget that is next to the one that contains the combobox sending me an indexChanged signal. (Basically I want to change the neighboring QStackWidgets index)
I thought that I would be able to simply store the QStackWidget in the childItem using setData and then retrieve it inside the indexChanged slot but for some reason it appears the QStackWidget is not set to the childItems data.
Any help is appreciated.
This is where I orginally setup my QTreeWidget and its Items
QTreeWidgetItem *childItem = new QTreeWidgetItem(itemParent);
QVariant itemParentVariant,widgetParentVarient;
widgetParentVarient.setValue(widgetParent);
itemParentVariant.setValue(itemParent);
QList<QVariant> stackWidgetList;
uint cycleSetup;
for(cycleSetup = 0;cycleSetup < methodBlocks.at(rowType).size()+2;cycleSetup++)
{
QComboBox *itemComboBox = new QComboBox;
itemComboBox->setProperty("rowType", rowType);
itemComboBox->setProperty("row", 0);
itemComboBox->setProperty("column",cycleSetup);
itemComboBox->setProperty("widgetParent",widgetParentVarient);
itemComboBox->setProperty("itemParent",itemParentVariant);
itemComboBox->addItems(methodBlocks.at(0).at(cycleSetup));
QObject::connect(itemComboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(OnComboIndexChanged(const QString&)));
QLineEdit *itemLineEdit = new QLineEdit;
QPushButton *itemButton = new QPushButton;
itemButton->setText("Reset");
QComboBox *timeComboBox = new QComboBox;
timeComboBox->setProperty("rowType", rowType);
timeComboBox->setProperty("row", 0);
timeComboBox->setProperty("column",cycleSetup);
timeComboBox->setProperty("widgetParent",widgetParentVarient);
timeComboBox->setProperty("itemParent",itemParentVariant);
timeComboBox->addItems(QString("Seconds;MilliSeconds;Reset").split(";"));
QStackedWidget *masterItemWidget = new QStackedWidget;
masterItemWidget->addWidget(itemLineEdit);
masterItemWidget->addWidget(itemComboBox);
masterItemWidget->addWidget(itemButton);
masterItemWidget->addWidget(timeComboBox);
masterItemWidget->setCurrentIndex(1);
QVariant stackParent;
stackParent.setValue(masterItemWidget);
itemComboBox->setProperty("stackParent",stackParent);
childItem->setData(0,Qt::UserRole,stackParent);
stackWidgetList.push_back(stackParent);
widgetParent->setItemWidget(childItem,cycleSetup,masterItemWidget);
itemParent->addChild(childItem);
}
And this is inside the slot where I am trying to retrieve the data (The QStackWidget)
QStackedWidget *itemMaster = combo->property("stackParent").value<QStackedWidget*>(); //this works
itemMaster->setCurrentIndex(0);
QTreeWidget *widgetParent = combo->property("widgetParent").value<QTreeWidget*>();
QTreeWidgetItem *parentItem = combo->property("itemParent").value<QTreeWidgetItem*>();
QTreeWidgetItem *childItem = new QTreeWidgetItem(parentItem);
QList<QVariant> stackList = childItem->data(0,Qt::UserRole).value<QList<QVariant>>(); //this doesnt
QStackedWidget *itemsibMaster = childItem->data(0,Qt::UserRole).value<QStackedWidget*>(); //neither does this
itemsibMaster->setCurrentIndex(2);
EDIT:
I've tried to set the data like this
QFrame *stackFrame = new QFrame;
QStackedWidget *masterItemWidget = new QStackedWidget(stackFrame);
masterItemWidget->addWidget(itemLineEdit);
masterItemWidget->addWidget(itemComboBox);
masterItemWidget->addWidget(itemButton);
masterItemWidget->addWidget(timeComboBox);
masterItemWidget->setCurrentIndex(1);
QVariant stackParent;
stackParent.setValue(masterItemWidget);
itemComboBox->setProperty("stackParent",stackParent);
QVariant frameVariant;
frameVariant.setValue(stackFrame);
childItem->setData(0,Qt::UserRole,frameVariant);
stackWidgetList.push_back(stackParent);
widgetParent->setItemWidget(childItem,cycleSetup,masterItemWidget);
itemParent->addChild(childItem);
And retrieve it like this
QStackedWidget *itemMaster = combo->property("stackParent").value<QStackedWidget*>();
itemMaster->setCurrentIndex(0);
QTreeWidget *widgetParent = combo->property("widgetParent").value<QTreeWidget*>();
QTreeWidgetItem *parentItem = combo->property("itemParent").value<QTreeWidgetItem*>();
QTreeWidgetItem *childItem = new QTreeWidgetItem(parentItem);
QFrame *frameObject = childItem->data(0,Qt::UserRole).value<QFrame*>();
//QList<QVariant> stackList = childItem->data(0,Qt::UserRole).value<QList<QVariant>>();
QStackedWidget *itemFrameMaster = frameObject->findChild<QStackedWidget*>();
if(itemFrameMaster)
{
qDebug() << "itemFrame Exists";
}
else
{
qDebug() << "itemFrame is NULL";//It goes to here
}
So I'm still unable to get the desired functionality.
Check if it works.
As stacked widget QStackedWidget derived from QFrame, Create a Frame object and add your stacked widget to it. Set the frame to your child item.
QFrame *stackFrame = new QFrame(Parent);
QStackedWidget *masterItemWidget = new QStackedWidget(stackFrame);
While querying first query for the frame and get the stacked widget child from it.
QStackedWidget *stackedWidget = FrameObject->findChild<QStackedWidget *>();
Alright so I managed to get the functionality that I was after, so in case anyone else is trying to do this here's the fix.
Essentially everything I had done before was correct except for one error.
When retrieving the data stored in the comboboxes child I had originally gotten that child here.
QTreeWidgetItem *parentItem = combo->property("itemParent").value<QTreeWidgetItem*>();
QTreeWidgetItem *childItem = new QTreeWidgetItem(parentItem);
The issue was that since the parentItem had more than one child (I suppose in this case the minimum is two children) I was not referencing the correct child. This issue was solved by creating a custom combobox property which held the child rather than the parent (parent can be derived from the parent more accurately than visa versa).
Now where I populate the QTreeWidget with combobox items looks like this.
QTreeWidgetItem *childItem = new QTreeWidgetItem(itemParent);
QVariant childItemVariant,widgetParentVarient;
widgetParentVarient.setValue(widgetParent);
childItemVariant.setValue(childItem);
uint cycleSetup;
for(cycleSetup = 0;cycleSetup < methodBlocks.at(rowType).size();cycleSetup++)
{
if(cycleSetup < methodBlocks.at(rowType).size())
{
QComboBox *itemComboBox = new QComboBox;
itemComboBox->setProperty("rowType", rowType);
itemComboBox->setProperty("row", 0);
itemComboBox->setProperty("column",cycleSetup);
itemComboBox->setProperty("widgetParent",widgetParentVarient);
itemComboBox->setProperty("childItem",childItemVariant);
itemComboBox->addItems(methodBlocks.at(0).at(cycleSetup));
QObject::connect(itemComboBox, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(OnComboIndexChanged(const QString&)));
QLineEdit *itemLineEdit = new QLineEdit;
QFrame *stackFrame = new QFrame;
QStackedWidget *masterItemWidget = new QStackedWidget(stackFrame);
masterItemWidget->addWidget(itemLineEdit);
masterItemWidget->addWidget(itemComboBox);
//masterItemWidget->addWidget(timeComboBox);
masterItemWidget->setCurrentIndex(1);
QVariant stackParent;
stackParent.setValue(masterItemWidget);
itemComboBox->setProperty("stackParent",stackParent);
itemComboBox->setProperty("cycleSetupIT",cycleSetup);
QVariant frameVariant;
frameVariant.setValue(stackFrame);
childItem->setData(cycleSetup,Qt::UserRole,stackParent);
widgetParent->setItemWidget(childItem,cycleSetup,masterItemWidget);
itemParent->addChild(childItem);
}
}
}
And the code in the slot where I get the data from the childItem (which holds the combobox) looks like this.
QTreeWidget *widgetParent = combo->property("widgetParent").value<QTreeWidget*>();
widgetParent->setColumnCount(6);
QTreeWidgetItem *childItem = combo->property("childItem").value<QTreeWidgetItem*>();
QTreeWidgetItem *parentItem = childItem->parent();
int rowType = combo->property("rowType").toInt();
int cycleIT = combo->property("cycleSetupIT").toInt();
int offset = 0;
QStackedWidget *itemFrameMaster = childItem->data(cycleIT+1,Qt::UserRole).value<QStackedWidget*>();
itemFrameMaster->setCurrentIndex(0);
Hope this helps. Also if anyone knows how to get the number of data items in a QStandardItem::data() that'd be great albeit not super critical.
Cheers!
In QtCreater I added a table to my project. in my code I am generating some data to output into the table. I want to add a QCheckbox into each row to allow the row to be selected. All the content of the table is aligned left, how do I make only these checkboxes in the first column of every row align to the center?
I'm adding the QCheckbox using:
ui->data_table->setCellWidget(rowCount,0, new QCheckBox);
Two thumbs up for Barry Mavin! You don't even have to subclass.
one line...
pCheckBox->setStyleSheet("margin-left:50%; margin-right:50%;");
done!!
I usually use a layout and a container widget for this. It is an ugly solution, but it works:
QWidget * w = new QWidget();
QHBoxLayout *l = new QHBoxLayout();
l->setAlignment( Qt::AlignCenter );
l->addWidget( <add your checkbox here> );
w->setLayout( l );
ui->data_table->setCellWidget(rowCount,0, w);
So basically you will have:
Table Cell -> Widget -> Layout -> Checkbox
you'll have to consider it if you will need to access the checkbox through the table.
This is an old post but in fact there is a much easier and lighter way of achieving this, just subclass QCheckBox and set the stylesheet to
margin-left:50%;
margin-right:50%;
It works for me, but my checkbox is not completely displayed.
To have a complete view of the widget, remove margins in layout :
l->setContentsMargins(0,0,0,0);
As stated in similar question around Stack Overflow, it's currently an open BUG:
https://bugreports.qt-project.org/browse/QTBUG-5368
can be center like this too using layout if want to add more customization
// Create a widget that will contain a checkbox
QWidget *checkBoxWidget = new QWidget();
QCheckBox *checkBox = new QCheckBox(); // We declare and initialize the checkbox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
layoutCheckBox->addWidget(checkBox); // Set the checkbox in the layer
layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox
layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding
ui->my_table_view->setCellWidget(row_number,column_number, checkBoxWidget); // set cell widget
OR simply add left right margins
checkBox->setStyleSheet("margin-left:50%; margin-right:50%;");
#if QT_VERSION < 0x046000
#include <QCommonStyle>
class MyStyle : public QCommonStyle {
public:
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QCommonStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QCommonStyle::subElementRect(subElement, option, widget);
}
}
};
#else
#include <QProxyStyle>
#include <QStyleFactory>
class MyStyle: public QProxyStyle {
public:
MyStyle():QProxyStyle(QStyleFactory::create("Fusion")) {}
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QProxyStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QProxyStyle::subElementRect(subElement, option, widget);
}
}
};
#endif
QCheckBox *box = new QCheckBox();
box->setStyle(new MyStyle());
In QtCreater I added a table to my project. in my code I am generating some data to output into the table. I want to add a QCheckbox into each row to allow the row to be selected. All the content of the table is aligned left, how do I make only these checkboxes in the first column of every row align to the center?
I'm adding the QCheckbox using:
ui->data_table->setCellWidget(rowCount,0, new QCheckBox);
Two thumbs up for Barry Mavin! You don't even have to subclass.
one line...
pCheckBox->setStyleSheet("margin-left:50%; margin-right:50%;");
done!!
I usually use a layout and a container widget for this. It is an ugly solution, but it works:
QWidget * w = new QWidget();
QHBoxLayout *l = new QHBoxLayout();
l->setAlignment( Qt::AlignCenter );
l->addWidget( <add your checkbox here> );
w->setLayout( l );
ui->data_table->setCellWidget(rowCount,0, w);
So basically you will have:
Table Cell -> Widget -> Layout -> Checkbox
you'll have to consider it if you will need to access the checkbox through the table.
This is an old post but in fact there is a much easier and lighter way of achieving this, just subclass QCheckBox and set the stylesheet to
margin-left:50%;
margin-right:50%;
It works for me, but my checkbox is not completely displayed.
To have a complete view of the widget, remove margins in layout :
l->setContentsMargins(0,0,0,0);
As stated in similar question around Stack Overflow, it's currently an open BUG:
https://bugreports.qt-project.org/browse/QTBUG-5368
can be center like this too using layout if want to add more customization
// Create a widget that will contain a checkbox
QWidget *checkBoxWidget = new QWidget();
QCheckBox *checkBox = new QCheckBox(); // We declare and initialize the checkbox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
layoutCheckBox->addWidget(checkBox); // Set the checkbox in the layer
layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox
layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding
ui->my_table_view->setCellWidget(row_number,column_number, checkBoxWidget); // set cell widget
OR simply add left right margins
checkBox->setStyleSheet("margin-left:50%; margin-right:50%;");
#if QT_VERSION < 0x046000
#include <QCommonStyle>
class MyStyle : public QCommonStyle {
public:
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QCommonStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QCommonStyle::subElementRect(subElement, option, widget);
}
}
};
#else
#include <QProxyStyle>
#include <QStyleFactory>
class MyStyle: public QProxyStyle {
public:
MyStyle():QProxyStyle(QStyleFactory::create("Fusion")) {}
QRect subElementRect(SubElement subElement, const QStyleOption *option, const QWidget *widget = 0) const {
switch(subElement) {
case QStyle::SE_CheckBoxIndicator: {
QRect r = QProxyStyle::subElementRect(subElement, option, widget);
r.setRect( (widget->width() - r.width())/2, r.top(), r.width(), r.height());
return QRect(r);
}
default: return QProxyStyle::subElementRect(subElement, option, widget);
}
}
};
#endif
QCheckBox *box = new QCheckBox();
box->setStyle(new MyStyle());
How can I add a checkbox/radiobutton/combobox to a QTableWidget or a QListWidget?
There are two methods:
void QTableWidget::setCellWidget(int row, int column, QWidget* widget)
and
void QListWidget::setItemWidget(QListWidgetItem* item, QWidget* widget)
They allow to insert any widget and other controls that inherit QWidget. Checkbox/radio button/combobox do inherit from QWidget.
For a checkbox using the item's setCheckState method should do what you need both for list and table widgets. See if code below would work for you:
List widget:
QListWidgetItem *item0 = new QListWidgetItem(tr("First"), listWidget);
QListWidgetItem *item1 = new QListWidgetItem(tr("Second"), listWidget);
item0->setCheckState(Qt::Unchecked);
item1->setCheckState(Qt::Checked);
Table widget:
QTableWidgetItem *item2 = new QTableWidgetItem("Item2");
item2->setCheckState(Qt::Checked);
tableWidget->setItem(0, 0, item2);
You can use delegates (QItemDelegate) for other types of editor's widgets, example is here: Spin Box Delegate Example.
I hope this helps.
you can add checkbox like this too
#include <QCheckBox>
void addCheckBoxAt(int row_number, int column_number,int state)
{
// Create a widget that will contain a checkbox
QWidget *checkBoxWidget = new QWidget();
QCheckBox *checkBox = new QCheckBox(); // We declare and initialize the checkbox
QHBoxLayout *layoutCheckBox = new QHBoxLayout(checkBoxWidget); // create a layer with reference to the widget
layoutCheckBox->addWidget(checkBox); // Set the checkbox in the layer
layoutCheckBox->setAlignment(Qt::AlignCenter); // Center the checkbox
layoutCheckBox->setContentsMargins(0,0,0,0); // Set the zero padding
/* Check on the status of odd if an odd device,
* exhibiting state of the checkbox in the Checked, Unchecked otherwise
* */
if(state == 1){
checkBox->setChecked(true);
} else {
checkBox->setChecked(false);
}
ui->job_table_view->setCellWidget(row_number,column_number, checkBoxWidget);
// Another way to add check box as item
/*
// QTableWidgetItem *checkBoxItem = new QTableWidgetItem("checkbox string ");
QTableWidgetItem *checkBoxItem = new QTableWidgetItem();
checkBoxItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
checkBoxItem->setCheckState(Qt::Checked);
ui->job_table_view->setItem(row_number,column_number,checkBoxItem);
*/
}
// call it like
addCheckBoxAt(0,0,1); // insert checkbox it 0,0 and check status true