问题描述
我正在编写PyQt应用程序,但在创建自定义列表视图时遇到了一些麻烦.我希望列表包含任意小部件(特别是一个自定义小部件).我该怎么办?
I'm writing a PyQt application and am having some trouble creating a custom list view. I'd like the list to contain arbitrary widgets (one custom widget in particular). How would I go about this?
似乎替代方法是创建一个包装在滚动条中的表或网格视图.但是,我希望能够利用模型/视图方法以及嵌套(树视图)支持内置句柄的优势.
It seems that the alternative would be to create a table or grid view wrapped in a scrollbar. However, I'd like to be able to take advantage of the model/view approach as well as the nesting (tree-view) support the built-ins handle.
为澄清起见,自定义窗口小部件是交互式的(包含按钮),因此该解决方案需要的不仅仅是绘制窗口小部件.
To clarify, the custom widgets are interactive (contain buttons), so the solution requires more than painting a widget.
推荐答案
我认为您需要继承 QItemDelegate .
此代码摘自Qt的示例(torrent应用程序).
This code is taken from Qt's examples, the torrent application.
class TorrentViewDelegate : public QItemDelegate
{
Q_OBJECT
public:
inline TorrentViewDelegate(MainWindow *mainWindow) : QItemDelegate(mainWindow) {}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
if (index.column() != 2) {
QItemDelegate::paint(painter, option, index);
return;
}
// Set up a QStyleOptionProgressBar to precisely mimic the
// environment of a progress bar.
QStyleOptionProgressBar progressBarOption;
progressBarOption.state = QStyle::State_Enabled;
progressBarOption.direction = QApplication::layoutDirection();
progressBarOption.rect = option.rect;
progressBarOption.fontMetrics = QApplication::fontMetrics();
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.textAlignment = Qt::AlignCenter;
progressBarOption.textVisible = true;
// Set the progress and text values of the style option.
int progress = qobject_cast<MainWindow *>(parent())->clientForRow(index.row())->progress();
progressBarOption.progress = progress < 0 ? 0 : progress;
progressBarOption.text = QString().sprintf("%d%%", progressBarOption.progress);
// Draw the progress bar onto the view.
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
}
};
基本上可以看到,它检查要绘制的列是否具有特定索引,如果是,则它绘制进度条.我认为您可以对其进行一些调整,而不是使用QStyleOption,而可以使用自己的小部件.
Basically as you can see it checks if the column to be painted is of a specific index, if so it paints a progress bar. I think you could tweak it a little and instead of using a QStyleOption you could use your own widget.
不要忘记使用 setItemDelegate .
在调查您的问题时,我偶然发现了此线程,它详细说明了如何使用QItemDelegate绘制自定义窗口小部件,我相信它具有您可能需要的所有信息.
While investigating your question I've stumbled upon this thread, which elaborates how to paint a custom widget using a QItemDelegate, I believe it has all the info you might need.
这篇关于具有自定义项目和自定义项目小部件的QListView/QListWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!